diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake index 781968ee59..21ce7aebab 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake @@ -1,460 +1,453 @@ set(SRC_CPP_FILES berryAbstractSourceProvider.cpp berryAbstractUICTKPlugin.cpp berryConstants.cpp berryDisplay.cpp berryEditorPart.cpp berryFileEditorInput.cpp berryGeometry.cpp berryIActionBars.h berryIContextService.cpp berryIContributionRoot.h berryIDropTargetListener.cpp berryIEditorDescriptor.cpp berryIEditorInput.cpp berryIEditorMatchingStrategy.cpp berryIEditorPart.cpp berryIEditorReference.cpp berryIEditorRegistry.cpp berryIEditorSite.cpp berryIFileEditorMapping.cpp berryIFolderLayout.cpp - berryImageDescriptor.cpp berryIMemento.cpp berryINullSelectionListener.cpp berryIPageLayout.cpp berryIPartListener.cpp berryIPageService.cpp berryIPartService.cpp berryIPathEditorInput.cpp berryIPerspectiveDescriptor.cpp berryIPerspectiveFactory.cpp berryIPerspectiveListener.cpp berryIPerspectiveRegistry.cpp berryIPlaceholderFolderLayout.cpp berryIPluginContribution.h berryIPostSelectionProvider.cpp berryIPreferencePage.cpp berryIPropertyChangeListener.cpp berryIQtPreferencePage.cpp berryIQtStyleManager.cpp berryIReusableEditor.cpp berryISaveablePart.cpp berryISaveablesLifecycleListener.cpp berryISaveablesSource.cpp berryISelection.cpp berryISelectionChangedListener.cpp berryISelectionListener.cpp berryISelectionProvider.cpp berryISelectionService.cpp berryIShellListener.cpp berryIShellProvider.cpp berryIShowInSource.h berryIShowInTarget.h berryISizeProvider.cpp berryISourceProvider.cpp berryISourceProviderListener.cpp berryISources.cpp berryIStickyViewDescriptor.cpp berryIStructuredSelection.cpp berryIViewCategory.cpp berryIViewDescriptor.cpp berryIViewLayout.cpp berryIViewPart.cpp berryIViewReference.cpp berryIViewRegistry.cpp berryIViewSite.cpp berryIWorkbenchCommandConstants.cpp berryIWindowListener.cpp berryIWorkbench.cpp berryIWorkbenchListener.cpp berryIWorkbenchPage.cpp berryIWorkbenchPart.cpp berryIWorkbenchPartConstants.cpp berryIWorkbenchPartDescriptor.cpp berryIWorkbenchPartReference.cpp berryIWorkbenchPartSite.cpp berryIWorkbenchSite.cpp berryIWorkbenchWindow.cpp berryMenuUtil.cpp berryPlatformUI.cpp berryPoint.cpp berryPropertyChangeEvent.cpp berryQModelIndexObject.cpp berryQtEditorPart.cpp berryQtItemSelection.cpp berryQtIntroPart.cpp berryQtPreferences.cpp berryQtSelectionProvider.cpp berryQtViewPart.cpp berryRectangle.cpp berrySameShellProvider.cpp berrySaveable.cpp berrySaveablesLifecycleEvent.cpp berrySelectionChangedEvent.cpp berryShell.cpp berryShellEvent.cpp berryShowInContext.cpp berryUIException.cpp berryViewPart.cpp berryWindow.cpp berryWorkbenchActionConstants.cpp berryWorkbenchPart.cpp berryWorkbenchPreferenceConstants.cpp berryXMLMemento.cpp #actions actions/berryAbstractContributionFactory.cpp actions/berryAbstractGroupMarker.cpp actions/berryCommandContributionItem.h actions/berryCommandContributionItem.cpp actions/berryContributionItem.cpp actions/berryContributionItemFactory.cpp actions/berryContributionManager.cpp actions/berryIContributionItem.h actions/berryIContributionManager.h actions/berryIContributionManagerOverrides.cpp actions/berryIMenuManager.h #actions/berryMenuBarManager.cpp actions/berryMenuManager.cpp actions/berrySeparator.cpp actions/berrySubContributionItem.cpp #application application/berryActionBarAdvisor.cpp application/berryIActionBarConfigurer.cpp application/berryIWorkbenchConfigurer.cpp application/berryIWorkbenchWindowConfigurer.cpp application/berryWorkbenchAdvisor.cpp application/berryWorkbenchWindowAdvisor.cpp #commands commands/berryICommandImageService.cpp commands/berryICommandService.cpp commands/berryIElementReference.h commands/berryIElementUpdater.h commands/berryIMenuService.h commands/berryUIElement.cpp #guitk guitk/berryGuiTkControlEvent.cpp guitk/berryGuiTkEvent.cpp guitk/berryGuiTkIControlListener.cpp guitk/berryGuiTkIMenuListener.cpp guitk/berryGuiTkISelectionListener.cpp guitk/berryGuiTkSelectionEvent.cpp #handlers handlers/berryHandlerUtil.cpp handlers/berryIHandlerActivation.cpp handlers/berryIHandlerService.cpp handlers/berryRadioState.cpp handlers/berryRegistryToggleState.cpp handlers/berryShowViewHandler.cpp handlers/berryToggleState.cpp #intro intro/berryIIntroManager.cpp intro/berryIIntroPart.cpp intro/berryIIntroSite.cpp intro/berryIntroPart.cpp #tweaklets tweaklets/berryDnDTweaklet.cpp tweaklets/berryGuiWidgetsTweaklet.cpp - tweaklets/berryImageTweaklet.cpp tweaklets/berryITracker.cpp tweaklets/berryWorkbenchPageTweaklet.cpp tweaklets/berryWorkbenchTweaklet.cpp #presentations presentations/berryIPresentablePart.cpp presentations/berryIPresentationFactory.cpp presentations/berryIPresentationSerializer.cpp presentations/berryIStackPresentationSite.cpp presentations/berryStackDropResult.cpp presentations/berryStackPresentation.cpp #services services/berryIDisposable.cpp services/berryIEvaluationReference.h services/berryIEvaluationService.cpp services/berryINestable.cpp services/berryIServiceFactory.cpp services/berryIServiceLocator.cpp services/berryIServiceScopes.cpp services/berryIServiceWithSources.cpp services/berryISourceProviderService.cpp #testing testing/berryTestableObject.cpp #util util/berryISafeRunnableRunner.cpp util/berrySafeRunnable.cpp # application application/berryQtWorkbenchAdvisor.cpp ) set(INTERNAL_CPP_FILES defaultpresentation/berryEmptyTabFolder.cpp defaultpresentation/berryEmptyTabItem.cpp defaultpresentation/berryNativeTabFolder.cpp defaultpresentation/berryNativeTabItem.cpp defaultpresentation/berryQCTabBar.cpp defaultpresentation/berryQtWorkbenchPresentationFactory.cpp util/berryAbstractTabFolder.cpp util/berryAbstractTabItem.cpp util/berryIPresentablePartList.cpp util/berryLeftToRightTabOrder.cpp util/berryPartInfo.cpp util/berryPresentablePartFolder.cpp util/berryReplaceDragHandler.cpp util/berryTabbedStackPresentation.cpp util/berryTabDragHandler.cpp util/berryTabFolderEvent.cpp util/berryTabOrder.cpp #intro intro/berryEditorIntroAdapterPart.cpp intro/berryIIntroDescriptor.cpp intro/berryIIntroRegistry.cpp intro/berryIntroConstants.cpp intro/berryIntroDescriptor.cpp intro/berryIntroPartAdapterSite.cpp intro/berryIntroRegistry.cpp intro/berryViewIntroAdapterPart.cpp intro/berryWorkbenchIntroManager.cpp berryAbstractMenuAdditionCacheEntry.cpp berryAbstractPartSelectionTracker.cpp berryAbstractSelectionService.cpp berryActivePartExpression.cpp berryAlwaysEnabledExpression.cpp berryAndExpression.cpp berryBundleUtility.cpp berryCommandContributionItemParameter.cpp berryCommandParameter.cpp berryCommandPersistence.cpp berryCommandService.cpp berryCommandServiceFactory.cpp berryCommandStateProxy.cpp berryCompositeExpression.cpp berryContainerPlaceholder.cpp berryContributionRoot.cpp berryDetachedPlaceHolder.cpp berryDefaultSaveable.cpp berryDefaultStackPresentationSite.cpp berryDetachedWindow.cpp berryDragUtil.cpp berryEditorAreaHelper.cpp berryEditorDescriptor.cpp berryEditorManager.cpp berryEditorReference.cpp berryEditorRegistry.cpp berryEditorRegistryReader.cpp berryEditorSashContainer.cpp berryEditorSite.cpp berryElementReference.cpp berryErrorViewPart.cpp berryEvaluationAuthority.cpp berryEvaluationReference.cpp berryEvaluationResultCache.cpp berryEvaluationService.cpp berryExpressionAuthority.cpp berryFileEditorMapping.cpp berryFolderLayout.cpp berryHandlerActivation.cpp berryHandlerAuthority.cpp berryHandlerPersistence.cpp berryHandlerProxy.cpp berryHandlerService.cpp berryHandlerServiceFactory.cpp berryIDragOverListener.cpp berryIDropTarget.cpp berryIEvaluationResultCache.cpp berryILayoutContainer.cpp berryInternalMenuService.h berryIServiceLocatorCreator.cpp berryIStickyViewManager.cpp berryIWorkbenchLocationService.cpp berryLayoutHelper.cpp berryLayoutPart.cpp berryLayoutPartSash.cpp berryLayoutTree.cpp berryLayoutTreeNode.cpp berryMenuServiceFactory.cpp berryMMMenuListener.cpp berryNestableHandlerService.cpp berryNullEditorInput.cpp berryPageLayout.cpp berryPagePartSelectionTracker.cpp berryPageSelectionService.cpp berryParameterValueConverterProxy.cpp berryPartList.cpp berryPartPane.cpp berryPartPlaceholder.cpp berryPartSashContainer.cpp berryPartService.cpp berryPartSite.cpp berryPartStack.cpp berryPartTester.cpp berryPersistentState.cpp berryPerspective.cpp berryPerspectiveDescriptor.cpp berryPerspectiveExtensionReader.cpp berryPerspectiveHelper.cpp berryPerspectiveRegistry.cpp berryPerspectiveRegistryReader.cpp berryPlaceholderFolderLayout.cpp berryPreferenceConstants.cpp berryPresentablePart.cpp berryPresentationFactoryUtil.cpp berryPresentationSerializer.cpp berryQtControlWidget.cpp berryQtDnDControlWidget.cpp berryQtDisplay.cpp berryQtDnDTweaklet.cpp - berryQtFileImageDescriptor.cpp berryQtGlobalEventFilter.cpp - berryQtIconImageDescriptor.cpp - berryQtImageTweaklet.cpp berryQtMainWindowControl.cpp - berryQtMissingImageDescriptor.cpp berryQtOpenPerspectiveAction.cpp berryQtPerspectiveSwitcher.cpp berryQtSafeApplication.cpp berryQtSash.cpp berryQtShell.cpp berryQtShowViewAction.cpp berryQtShowViewDialog.cpp berryQtStyleManager.cpp berryQtStylePreferencePage.cpp berryQtTracker.cpp berryQtWidgetController.cpp berryQtWidgetsTweaklet.cpp berryQtWidgetsTweakletImpl.cpp berryQtWorkbenchPageTweaklet.cpp berryQtWorkbenchTweaklet.cpp berryRegistryPersistence.cpp berryRegistryReader.cpp berrySaveablesList.cpp berryShowViewMenu.cpp berryServiceLocator.cpp berryServiceLocatorCreator.cpp berryShellPool.cpp berrySlaveCommandService.cpp berrySlaveHandlerService.cpp berrySlaveMenuService.cpp berrySourceProviderService.cpp berrySourcePriorityNameMapping.cpp berryStatusUtil.cpp berryStickyViewDescriptor.cpp berryStickyViewManager.cpp berryTweaklets.cpp berryUtil.cpp berryViewDescriptor.cpp berryViewFactory.cpp berryViewLayout.cpp berryViewReference.cpp berryViewRegistry.cpp berryViewRegistryReader.cpp berryViewSashContainer.cpp berryViewSite.cpp berryWorkbenchPage.cpp berryWindowManager.cpp berryWindowPartSelectionTracker.cpp berryWindowSelectionService.cpp berryWorkbench.cpp berryWorkbenchConfigurer.cpp berryWorkbenchConstants.cpp berryWorkbenchLocationService.cpp berryWorkbenchMenuService.cpp berryWorkbenchPagePartList.cpp berryWorkbenchPartReference.cpp berryWorkbenchPlugin.cpp berryWorkbenchRegistryConstants.cpp berryWorkbenchServiceRegistry.cpp berryWorkbenchSourceProvider.cpp berryWorkbenchTestable.cpp berryWorkbenchWindow.cpp berryWorkbenchWindowConfigurer.cpp berryWorkbenchWindowExpression.cpp berryWWinActionBars.cpp berryWWinPartService.cpp ) set(MOC_H_FILES src/berryAbstractUICTKPlugin.h src/berryEditorPart.h src/berryQtSelectionProvider.h src/berryViewPart.h src/berryWorkbenchPart.h src/actions/berryCommandContributionItem.h src/intro/berryIntroPart.h src/handlers/berryShowViewHandler.h src/internal/berryCommandServiceFactory.h src/internal/berryHandlerServiceFactory.h src/internal/berryMenuServiceFactory.h src/internal/berryMMMenuListener.h src/internal/berryQtDisplay.h src/internal/berryQtDnDTweaklet.h src/internal/berryQtGlobalEventFilter.h - src/internal/berryQtImageTweaklet.h src/internal/berryQtMainWindowControl.h src/internal/berryQtOpenPerspectiveAction.h src/internal/berryQtPerspectiveSwitcher.h src/internal/berryQtSash.h src/internal/berryQtShowViewAction.h src/internal/berryQtStyleManager.h src/internal/berryQtStylePreferencePage.h src/internal/berryQtTracker.h src/internal/berryQtWidgetsTweaklet.h src/internal/berryQtWidgetsTweakletImpl.h src/internal/berryQtWorkbenchTweaklet.h src/internal/berryQtWorkbenchPageTweaklet.h src/internal/berryWorkbenchPlugin.h src/internal/berryWorkbenchSourceProvider.h src/internal/defaultpresentation/berryNativeTabFolder.h src/internal/defaultpresentation/berryNativeTabItem.h src/internal/defaultpresentation/berryQCTabBar.h src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h src/internal/intro/berryEditorIntroAdapterPart.h ) set(UI_FILES src/internal/berryQtShowViewDialog.ui src/internal/berryQtStylePreferencePage.ui src/internal/berryQtStatusPart.ui ) set(QRC_FILES resources/org_blueberry_ui_qt.qrc ) set(CACHED_RESOURCE_FILES plugin.xml ) set(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp index 014d771451..23e76d1407 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,736 +1,735 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCommandContributionItem.h" #include "berryIMenuService.h" #include "berryICommandService.h" #include "berryICommandImageService.h" #include "berryIContributionManager.h" #include "berryIElementReference.h" #include "berryIElementUpdater.h" #include "berryUIElement.h" #include #include #include #include #include #include #include -#include "../berryImageDescriptor.h" #include "../berryDisplay.h" #include "../berryAsyncRunnable.h" #include "../handlers/berryIHandlerService.h" #include "../services/berryIServiceLocator.h" #include "../internal/berryCommandContributionItemParameter.h" #include "../internal/berryWorkbenchPlugin.h" #include #include #include #include namespace berry { ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT; //class CommandUIElementListener : public IUIElementListener //{ //private: // CommandContributionItem* item; // public: // CommandUIElementListener(CommandContributionItem* item); // void UIElementDisposed(UIElement* item); //void UIElementSelected(SmartPointer item); //}; CommandContributionItem::CommandContributionItem( const SmartPointer& contributionParameters) : ContributionItem(contributionParameters->id) , action(0) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->tooltip = contributionParameters->tooltip; this->style = contributionParameters->style; this->helpContextId = contributionParameters->helpContextId; this->visibleEnabled = contributionParameters->visibleEnabled; this->mode = contributionParameters->mode; menuService = contributionParameters->serviceLocator->GetService(); commandService = contributionParameters->serviceLocator->GetService(); handlerService = contributionParameters->serviceLocator->GetService(); // bindingService = (IBindingService) contributionParameters.serviceLocator // .getService(IBindingService.class); this->CreateCommand(contributionParameters->commandId, contributionParameters->parameters); if (command) { try { class CommandUIElement : public UIElement { private: CommandContributionItem* item; public: CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator) : UIElement(serviceLocator), item(item) {} void SetText(const QString& text) { item->SetText(text); } void SetToolTip(const QString& text) { item->SetToolTip(text); } void SetIcon(const QIcon& icon) { item->SetIcon(icon); } void SetChecked(bool checked) { item->SetChecked(checked); } void SetDropDownId(const QString& id) { item->dropDownMenuOverride = id; } }; UIElement::Pointer callback(new CommandUIElement(this, contributionParameters->serviceLocator)); elementRef = commandService->RegisterElementForCommand(command, callback); command->GetCommand()->AddCommandListener(this->GetCommandListener()); this->SetImages(contributionParameters->serviceLocator, contributionParameters->iconStyle); if (contributionParameters->helpContextId.isEmpty()) { try { this->helpContextId = commandService->GetHelpContextId( contributionParameters->commandId); } catch (const NotDefinedException& /*e*/) { // it's OK to not have a helpContextId } } // IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator // ->GetService(IWorkbenchLocationService::GetManifestName()).Cast(); // const IWorkbench* workbench = wls->GetWorkbench();; // if (workbench != 0 && !helpContextId.empty()) { // this->workbenchHelpSystem = workbench->GetHelpSystem(); // } } catch (const NotDefinedException& /*e*/) { WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId() + "\", command \"" + contributionParameters->commandId + "\" not defined"); } } } QAction* CommandContributionItem::Fill(QMenu* parent, QAction* before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = 0; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(item, helpContextId); // } connect(item, SIGNAL(triggered()), this, SLOT(HandleWidgetSelection())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } QAction *CommandContributionItem::Fill(QToolBar *parent, QAction *before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } QAction* item = 0; if (before) { item = parent->addAction(icon, label); } else { item = new QAction(icon, label, parent); parent->insertAction(before, item); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); //item->AddListener(this->GetItemListener()); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } void CommandContributionItem::Update() { this->Update(QString()); } void CommandContributionItem::Update(const QString& /*id*/) { if (action) { QWidget* parent = action->parentWidget(); if(qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateToolItem(); } } } void CommandContributionItem::UpdateMenuItem() { QString text = label; if (text.isEmpty()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } text = UpdateMnemonic(text); // String keyBindingText = null; // if (command != null) // { // TriggerSequence binding = bindingService // .getBestActiveBindingFor(command); // if (binding != null) // { // keyBindingText = binding.format(); // } // } // if (text != null) // { // if (keyBindingText == null) // { // item.setText(text); // } // else // { // item.setText(text + '\t' + keyBindingText); // } // } if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } void CommandContributionItem::UpdateToolItem() { QString text = label; QString tooltip = label; if (text.isNull()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); tooltip = command->GetCommand()->GetDescription(); if (tooltip.trimmed().isEmpty()) { tooltip = text; } } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT) && !text.isNull()) { action->setText(text); } QString toolTipText = GetToolTipText(tooltip); action->setToolTip(toolTipText); if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } CommandContributionItem::~CommandContributionItem() { if (elementRef) { commandService->UnregisterElement(elementRef); } if (commandListener) { command->GetCommand()->RemoveCommandListener(commandListener.data()); } } bool CommandContributionItem::IsEnabled() const { if (command) { command->GetCommand()->SetEnabled(menuService->GetCurrentState()); return command->GetCommand()->IsEnabled(); } return false; } bool CommandContributionItem::IsVisible() const { if (visibleEnabled) { return ContributionItem::IsVisible() && this->IsEnabled(); } return ContributionItem::IsVisible(); } void CommandContributionItem::SetImages(IServiceLocator* locator, const QString& iconStyle) { if (icon.isNull()) { ICommandImageService* service = locator->GetService(); if (service) { icon = service->GetImage(command->GetId(), iconStyle); } } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} void CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; commandListener.reset(new MyCommandListener(this)); } return commandListener.data(); } void CommandContributionItem::UpdateCommandProperties(const SmartPointer< const CommandEvent> commandEvent) { if (commandEvent->IsHandledChanged()) { dropDownMenuOverride = ""; } if (!action) { return; } Display* display = Display::GetDefault(); typedef AsyncRunnable, CommandContributionItem > UpdateRunnable; Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent); if (display->InDisplayThread()) { update->run(); } else { display->AsyncExec(update); } } void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent) { if (commandEvent->GetCommand()->IsDefined()) { this->Update(); } if (commandEvent->IsEnabledChanged() || commandEvent->IsHandledChanged()) { if (visibleEnabled) { IContributionManager* parent = this->GetParent(); if (parent) { parent->Update(true); } } } } bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer& handler) { // if no handler or handler doesn't implement IElementUpdater, // restore the contributed elements if (handler.IsNull()) return true; if (!(handler.Cast())) return true; // special case, if its HandlerProxy, then check the actual handler // if (handler instanceof HandlerProxy) { // HandlerProxy handlerProxy = (HandlerProxy) handler; // IHandler actualHandler = handlerProxy.getHandler(); // return shouldRestoreAppearance(actualHandler); // } return false; } SmartPointer CommandContributionItem::GetCommand() const { return command; } void CommandContributionItem::CreateCommand(const QString &commandId, const QHash ¶meters) { if (commandId.isEmpty()) { // StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR, // "Unable to create menu item \"" + getId() // + "\", no command id", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", no command id"; return; } Command::Pointer cmd = commandService->GetCommand(commandId); if (!cmd->IsDefined()) { // StatusManager.getManager().handle(StatusUtil.newStatus( // IStatus.ERROR, "Unable to create menu item \"" + getId() // + "\", command \"" + commandId + "\" not defined", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", command \"" << commandId.toStdString() << "\" not defined"; return; } command = ParameterizedCommand::GenerateCommand(cmd, parameters); } QString CommandContributionItem::GetToolTipText(const QString& text) const { QString tooltipText = tooltip; if (tooltip.isNull()) { if (!text.isNull()) { tooltipText = text; } else { tooltipText = ""; } } // TriggerSequence activeBinding = bindingService // .getBestActiveBindingFor(command); // if (activeBinding != null && !activeBinding.isEmpty()) // { // String acceleratorText = activeBinding.format(); // if (acceleratorText != null // && acceleratorText.length() != 0) // { // tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator, // tooltipText, acceleratorText); // } // } return tooltipText; } QString CommandContributionItem::UpdateMnemonic(const QString &s) { if (mnemonic.isNull() || s.isEmpty()) { return s; } int idx = s.indexOf(mnemonic); if (idx == -1) { return s; } return s.left(idx) + '&' + s.mid(idx); } //SmartPointer CommandContributionItem::GetItemListener() //{ // if (!itemListener) // { // itemListener = new CommandUIElementListener(this); // } // return itemListener; //} void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; if ((style & STYLE_CHECK) != 0) { checkedState = action->isChecked(); } try { handlerService->ExecuteCommand(command, UIElement::Pointer(0)); } catch (const ExecutionException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotDefinedException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotEnabledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotHandledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } } void CommandContributionItem::connectNotify(const char *signal) { qDebug() << "Connected to:" << signal; } void CommandContributionItem::disconnectNotify(const char *signal) { qDebug() << "Disconnected from:" << signal; } //TODO Tool item drop down menu contributions //bool CommandContributionItem::OpenDropDownMenu(SmartPointer event) //{ //Widget item = event.widget; //if (item != null) //{ // int style = item.getStyle(); // if ((style & SWT.DROP_DOWN) != 0) // { // if (event.detail == 4) // { // on drop-down button // ToolItem ti = (ToolItem) item; // // final MenuManager menuManager = new MenuManager(); // Menu menu = menuManager.createContextMenu(ti.getParent()); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(menu, helpContextId); // } // menuManager.addMenuListener(new IMenuListener() // { // public void menuAboutToShow(IMenuManager manager) // { // String id = getId(); // if (dropDownMenuOverride != null) // { // id = dropDownMenuOverride; // } // menuService.populateContributionManager( // menuManager, "menu:" + id); //$NON-NLS-1$ // } // }); // // // position the menu below the drop down item // Point point = ti.getParent().toDisplay( // new Point(event.x, event.y)); // menu.setLocation(point.x, point.y); // waiting for SWT // // 0.42 // menu.setVisible(true); // return true; // we don't fire the action // } // } //} // //return false; //} void CommandContributionItem::SetIcon(const QIcon &icon) { this->icon = icon; this->UpdateIcons(); } void CommandContributionItem::UpdateIcons() { action->setIcon(icon); } void CommandContributionItem::SetText(const QString &text) { label = text; this->Update(); } void CommandContributionItem::SetChecked(bool checked) { if (checkedState == checked) { return; } checkedState = checked; action->setChecked(checkedState); } void CommandContributionItem::SetToolTip(const QString &text) { tooltip = text; action->setToolTip(text); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp index f856d850e6..74ba413dfe 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp @@ -1,281 +1,281 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryAbstractUICTKPlugin.h" #include "internal/berryBundleUtility.h" #include "internal/berryWorkbenchPlugin.h" -#include "berryImageDescriptor.h" #include "berryPlatformUI.h" #include "berryIPreferencesService.h" #include "berryIPreferences.h" #include #include namespace berry { const QString AbstractUICTKPlugin::FN_DIALOG_SETTINGS = "dialog_settings.xml"; AbstractUICTKPlugin::AbstractUICTKPlugin() : preferencesService(0) { } // IDialogSettings getDialogSettings() { // if (dialogSettings == null) { // loadDialogSettings(); // } // return dialogSettings; // } // ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = createImageRegistry(); // initializeImageRegistry(imageRegistry); // } // return imageRegistry; // } IPreferencesService* AbstractUICTKPlugin::GetPreferencesService() const { // Create the preference store lazily. if (preferencesService == 0) { ctkServiceReference serviceRef = m_Context->getServiceReference(); if (!serviceRef) { BERRY_ERROR << "Preferences service not available"; } preferencesService = m_Context->getService(serviceRef); } return preferencesService; } SmartPointer AbstractUICTKPlugin::GetPreferences() const { IPreferencesService* prefService = this->GetPreferencesService(); if (prefService == NULL) return IPreferences::Pointer(0); return prefService->GetSystemPreferences(); } IWorkbench* AbstractUICTKPlugin::GetWorkbench() { return PlatformUI::GetWorkbench(); } // ImageRegistry createImageRegistry() // { // // //If we are in the UI Thread use that // if (Display.getCurrent() != null) // { // return new ImageRegistry(Display.getCurrent()); // } // // if (PlatformUI.isWorkbenchRunning()) // { // return new ImageRegistry(PlatformUI.getWorkbench().getDisplay()); // } // // //Invalid thread access if it is not the UI Thread // //and the workbench is not created. // throw new SWTError(SWT.ERROR_THREAD_INVALID_ACCESS); // } // void initializeImageRegistry(ImageRegistry reg) { // // spec'ed to do nothing // } // void loadDialogSettings() { // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // // // bug 69387: The instance area should not be created (in the call to // // #getStateLocation) if -data @none or -data @noDefault was used // IPath dataLocation = getStateLocationOrNull(); // if (dataLocation != null) { // // try r/w state area in the local file system // String readWritePath = dataLocation.append(FN_DIALOG_SETTINGS) // .toOSString(); // File settingsFile = new File(readWritePath); // if (settingsFile.exists()) { // try { // dialogSettings.load(readWritePath); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } // // return; // } // } // // // otherwise look for bundle specific dialog settings // URL dsURL = BundleUtility.find(getBundle(), FN_DIALOG_SETTINGS); // if (dsURL == null) { // return; // } // // InputStream is = null; // try { // is = dsURL.openStream(); // BufferedReader reader = new BufferedReader( // new InputStreamReader(is, "utf-8")); //$NON-NLS-1$ // dialogSettings.load(reader); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // // do nothing // } // } // } // void refreshPluginActions() { // // If the workbench is not started yet, or is no longer running, do nothing. // if (!PlatformUI.isWorkbenchRunning()) { // return; // } // // // startup() is not guaranteed to be called in the UI thread, // // but refreshPluginActions must run in the UI thread, // // so use asyncExec. See bug 6623 for more details. // Display.getDefault().asyncExec(new Runnable() { // public void run() { // WWinPluginAction.refreshActionList(); // } // }); // } // void saveDialogSettings() { // if (dialogSettings == null) { // return; // } // // try { // IPath path = getStateLocationOrNull(); // if(path == null) { // return; // } // String readWritePath = path // .append(FN_DIALOG_SETTINGS).toOSString(); // dialogSettings.save(readWritePath); // } catch (IOException e) { // // spec'ed to ignore problems // } catch (IllegalStateException e) { // // spec'ed to ignore problems // } // } void AbstractUICTKPlugin::start(ctkPluginContext* context) { Plugin::start(context); // Should only attempt refreshPluginActions() once the bundle // has been fully started. Otherwise, action delegates // can be created while in the process of creating // a triggering action delegate (if UI events are processed during startup). // Also, if the start throws an exception, the bundle will be shut down. // We don't want to have created any delegates if this happens. // See bug 63324 for more details. // bundleListener = new BundleListener() // { // public void bundleChanged(BundleEvent event) // { // if (event.getBundle() == getBundle()) // { // if (event.getType() == BundleEvent.STARTED) // { // // We're getting notified that the bundle has been started. // // Make sure it's still active. It may have been shut down between // // the time this event was queued and now. // if (getBundle().getState() == Bundle.ACTIVE) // { // refreshPluginActions(); // } // fc.removeBundleListener(this); // } // } // } // }; // context.addBundleListener(bundleListener); // bundleListener is removed in stop(BundleContext) } void AbstractUICTKPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) // try // { // if (bundleListener != null) // { // context.removeBundleListener(bundleListener); // } // saveDialogSettings(); // savePreferenceStore(); // preferenceStore = null; // if (imageRegistry != null) // imageRegistry.dispose(); // imageRegistry = null; //} Plugin::stop(context); } -SmartPointer AbstractUICTKPlugin::ImageDescriptorFromPlugin( +QIcon AbstractUICTKPlugin::ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath) { if (pluginId.isEmpty() || imageFilePath.isEmpty()) { throw ctkInvalidArgumentException("argument cannot be empty"); } // if the plug-in is not ready then there is no image QSharedPointer plugin = BundleUtility::FindPlugin(pluginId); if (!BundleUtility::IsReady(plugin.data())) { - return ImageDescriptor::Pointer(0); + return QIcon(); } QByteArray imgContent = plugin->getResource(imageFilePath); QImage image = QImage::fromData(imgContent); QPixmap pixmap = QPixmap::fromImage(image); - QIcon* icon = new QIcon(pixmap); - if (icon->isNull()) - return ImageDescriptor::Pointer(0); + return QIcon(pixmap); +} - return ImageDescriptor::CreateFromImage(icon); +QIcon AbstractUICTKPlugin::GetMissingIcon() +{ + return QIcon(":/org.blueberry.ui.qt/icon_missing.png"); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h index 60ea407751..03656ca506 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h @@ -1,332 +1,294 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYABSTRACTUICTKPLUGIN_H_ #define BERRYABSTRACTUICTKPLUGIN_H_ #include #include namespace berry { template class SmartPointer; struct IPreferences; struct IPreferencesService; struct IWorkbench; -struct ImageDescriptor; - /** * \ingroup org_blueberry_ui_qt * * Abstract base class for plug-ins that integrate with the BlueBerry platform UI. *

* Subclasses obtain the following capabilities: *

*

* Preferences *

    *
  • The platform core runtime contains general support for plug-in * preferences (org.blueberry.core.runtime.Preferences). * This class provides appropriate conversion to the older JFace preference * API (org.blueberry.jface.preference.IPreferenceStore).
  • *
  • The method getPreferenceStore returns the JFace preference * store (cf. Plugin.getPluginPreferences which returns * a core runtime preferences object.
  • *
  • Subclasses may reimplement initializeDefaultPreferences * to set up any default values for preferences using JFace API. In this * case, initializeDefaultPluginPreferences should not be * overridden.
  • *
  • Subclasses may reimplement * initializeDefaultPluginPreferences to set up any default * values for preferences using core runtime API. In this * case, initializeDefaultPreferences should not be * overridden.
  • *
  • Preferences are also saved automatically on plug-in shutdown. * However, saving preferences immediately after changing them is * strongly recommended, since that ensures that preference settings * are not lost even in the event of a platform crash.
  • *
* Dialogs *
    *
  • The dialog store is read the first time getDialogSettings * is called.
  • *
  • The dialog store allows the plug-in to "record" important choices made * by the user in a wizard or dialog, so that the next time the * wizard/dialog is used the widgets can be defaulted to better values. A * wizard could also use it to record the last 5 values a user entered into * an editable combo - to show "recent values".
  • *
  • The dialog store is found in the file whose name is given by the * constant FN_DIALOG_STORE. A dialog store file is first * looked for in the plug-in's read/write state area; if not found there, * the plug-in's install directory is checked. * This allows a plug-in to ship with a read-only copy of a dialog store * file containing initial values for certain settings.
  • *
  • Plug-in code can call saveDialogSettings to cause settings to * be saved in the plug-in's read/write state area. A plug-in may opt to do * this each time a wizard or dialog is closed to ensure the latest * information is always safe on disk.
  • *
  • Dialog settings are also saved automatically on plug-in shutdown.
  • *
- * Images - *
    - *
  • A typical UI plug-in will have some images that are used very frequently - * and so need to be cached and shared. The plug-in's image registry - * provides a central place for a plug-in to store its common images. - * Images managed by the registry are created lazily as needed, and will be - * automatically disposed of when the plug-in shuts down. Note that the - * number of registry images should be kept to a minimum since many OSs - * have severe limits on the number of images that can be in memory at once. - *
*

* For easy access to your plug-in object, use the singleton pattern. Declare a * static variable in your plug-in class for the singleton. Store the first * (and only) instance of the plug-in class in the singleton when it is created. * Then access the singleton when needed through a static getDefault * method. *

*

* See the description on {@link Plugin}. *

*/ class BERRY_UI_QT AbstractUICTKPlugin : public Plugin { Q_OBJECT private: /** * The name of the dialog settings file (value * "dialog_settings.xml"). */ static const QString FN_DIALOG_SETTINGS; /** * Storage for dialog and wizard data; null if not yet * initialized. */ //DialogSettings dialogSettings = null; /** * Storage for preferences. */ mutable IPreferencesService* preferencesService; - /** - * The registry for all graphic images; null if not yet - * initialized. - */ - //ImageRegistry imageRegistry = null; - /** * The bundle listener used for kicking off refreshPluginActions(). */ //BundleListener bundleListener; public: /** * Creates an abstract UI plug-in runtime object. *

* Plug-in runtime classes are ctkPluginActivators and so must * have an default constructor. This method is called by the runtime when * the associated bundle is being activated. */ AbstractUICTKPlugin(); /** * Returns the dialog settings for this UI plug-in. * The dialog settings is used to hold persistent state data for the various * wizards and dialogs of this plug-in in the context of a workbench. *

* If an error occurs reading the dialog store, an empty one is quietly created * and returned. *

*

* Subclasses may override this method but are not expected to. *

* * @return the dialog settings */ // IDialogSettings getDialogSettings(); - /** - * Returns the image registry for this UI plug-in. - *

- * The image registry contains the images used by this plug-in that are very - * frequently used and so need to be globally shared within the plug-in. Since - * many OSs have a severe limit on the number of images that can be in memory at - * any given time, a plug-in should only keep a small number of images in their - * registry. - *

- * Subclasses should reimplement initializeImageRegistry if they have - * custom graphic images to load. - *

- *

- * Subclasses may override this method but are not expected to. - *

- * - * @return the image registry - */ -// ImageRegistry getImageRegistry(); - /** * Returns the preferences service for this UI plug-in. * This preferences service is used to hold persistent settings for this plug-in in * the context of a workbench. Some of these settings will be user controlled, * whereas others may be internal setting that are never exposed to the user. *

* If an error occurs reading the preferences service, an empty preference service is * quietly created, initialized with defaults, and returned. *

* * @return the preferences service */ IPreferencesService* GetPreferencesService() const; SmartPointer GetPreferences() const; /** * Returns the Platform UI workbench. *

* This method exists as a convenience for plugin implementors. The * workbench can also be accessed by invoking PlatformUI.getWorkbench(). *

* @return IWorkbench the workbench for this plug-in */ IWorkbench* GetWorkbench(); protected: /** * Returns a new image registry for this plugin-in. The registry will be * used to manage images which are frequently used by the plugin-in. *

* The default implementation of this method creates an empty registry. * Subclasses may override this method if needed. *

* * @return ImageRegistry the resulting registry. * @see #getImageRegistry */ // ImageRegistry createImageRegistry(); /** * Initializes an image registry with images which are frequently used by the * plugin. *

* The image registry contains the images used by this plug-in that are very * frequently used and so need to be globally shared within the plug-in. Since * many OSs have a severe limit on the number of images that can be in memory * at any given time, each plug-in should only keep a small number of images in * its registry. *

* Implementors should create a JFace image descriptor for each frequently used * image. The descriptors describe how to create/find the image should it be needed. * The image described by the descriptor is not actually allocated until someone * retrieves it. *

* Subclasses may override this method to fill the image registry. *

* @param reg the registry to initalize * * @see #getImageRegistry */ // void initializeImageRegistry(ImageRegistry reg); /** * Loads the dialog settings for this plug-in. * The default implementation first looks for a standard named file in the * plug-in's read/write state area; if no such file exists, the plug-in's * install directory is checked to see if one was installed with some default * settings; if no file is found in either place, a new empty dialog settings * is created. If a problem occurs, an empty settings is silently used. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void loadDialogSettings(); /** * Refreshes the actions for the plugin. * This method is called from startup. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void refreshPluginActions(); /** * Saves this plug-in's dialog settings. * Any problems which arise are silently ignored. */ // void saveDialogSettings(); public: /** * The AbstractUIPlugin implementation of this Plugin * method refreshes the plug-in actions. Subclasses may extend this method, * but must send super first. */ void start(ctkPluginContext* context); /** * The AbstractUIPlugin implementation of this Plugin * method saves this plug-in's preference and dialog stores and shuts down * its image registry (if they are in use). Subclasses may extend this * method, but must send super last. A try-finally statement should * be used where necessary to ensure that super.shutdown() is * always done. */ void stop(ctkPluginContext* context); /** * Creates and returns a new image descriptor for an image file located * within the specified plug-in. *

* This is a convenience method that simply locates the image file in * within the plug-in (no image registries are involved). The path is * relative to the root of the plug-in, and takes into account files * coming from plug-in fragments. The path may include $arg$ elements. * However, the path must not have a leading "." or path separator. * Clients should use a path like "icons/mysample.gif" rather than * "./icons/mysample.gif" or "/icons/mysample.gif". *

* * @param pluginId the id of the plug-in containing the image file; * null is returned if the plug-in does not exist * @param imageFilePath the relative path of the image file, relative to the * root of the plug-in; the path must be legal * @return an image descriptor, or null if no image * could be found - * @since 3.0 */ - static SmartPointer ImageDescriptorFromPlugin( + static QIcon ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath); + static QIcon GetMissingIcon(); }; } // namespace berry #endif /*BERRYABSTRACTUICTKPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.cpp index 753ac22d8b..bdc9c04a00 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.cpp @@ -1,101 +1,100 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEditorPart.h" -#include "berryImageDescriptor.h" #include "berryIWorkbenchPartConstants.h" #include namespace berry { EditorPart::EditorPart() { } void EditorPart::SetInput(IEditorInput::Pointer input) { editorInput = input; } void EditorPart::SetInputWithNotify(IEditorInput::Pointer input) { if (input != editorInput) { editorInput = input; FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT); } } void EditorPart::SetContentDescription(const QString& description) { // if (compatibilityTitleListener != null) // { // removePropertyListener(compatibilityTitleListener); // compatibilityTitleListener = null; // } WorkbenchPart::SetContentDescription(description); } void EditorPart::SetPartName(const QString& partName) { // if (compatibilityTitleListener != null) // { // removePropertyListener(compatibilityTitleListener); // compatibilityTitleListener = null; // } WorkbenchPart::SetPartName(partName); } void EditorPart::CheckSite(IWorkbenchPartSite::Pointer site) { WorkbenchPart::CheckSite(site); assert(!site.Cast().IsNull()); // The site for an editor must be an IEditorSite } IEditorInput::Pointer EditorPart::GetEditorInput() const { return editorInput; } IEditorSite::Pointer EditorPart::GetEditorSite() const { return this->GetSite().Cast(); } QString EditorPart::GetTitleToolTip() const { if (editorInput.IsNull()) { return WorkbenchPart::GetTitleToolTip(); } else { return editorInput->GetToolTipText(); } } bool EditorPart::IsSaveOnCloseNeeded() const { return this->IsDirty(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h index 2ec27bd1df..f9582311c2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h @@ -1,124 +1,122 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPERSPECTIVEDESCRIPTOR_H_ #define BERRYIPERSPECTIVEDESCRIPTOR_H_ #include #include #include -#include "berryImageDescriptor.h" - namespace berry { /** * \ingroup org_blueberry_ui_qt * * A perspective descriptor describes a perspective in an * IPerspectiveRegistry. *

* A perspective is a template for view visibility, layout, and action visibility * within a workbench page. There are two types of perspective: a predefined * perspective and a custom perspective. *

    *
  • A predefined perspective is defined by an extension to the workbench's * perspective extension point ("org.blueberry.ui.perspectives"). * The extension defines a id, label, and IPerspectiveFactory. * A perspective factory is used to define the initial layout for a page. *
  • *
  • A custom perspective is defined by the user. In this case a predefined * perspective is modified to suit a particular task and saved as a new * perspective. The attributes for the perspective are stored in a separate file * in the workbench's metadata directory. *
  • *
*

*

* Within a page the user can open any of the perspectives known * to the workbench's perspective registry, typically by selecting one from the * workbench's Open Perspective menu. When selected, the views * and actions within the active page rearrange to reflect the perspective. *

*

* This interface is not intended to be implemented by clients. *

* @see IPerspectiveRegistry * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPerspectiveDescriptor : public Object { berryObjectMacro(berry::IPerspectiveDescriptor) virtual ~IPerspectiveDescriptor(); /** * Returns the description of this perspective. * This is the value of its "description" attribute. * * @return the description * @since 3.0 */ virtual QString GetDescription() const = 0; /** * Returns this perspective's id. For perspectives declared via an extension, * this is the value of its "id" attribute. * * @return the perspective id */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image to show for this perspective. * If the extension for this perspective specifies an image, the descriptor * for it is returned. Otherwise a default image is returned. * * @return the descriptor of the image to show for this perspective */ - virtual ImageDescriptor::Pointer GetImageDescriptor() const = 0; + virtual QIcon GetImageDescriptor() const = 0; /** * Returns this perspective's label. For perspectives declared via an extension, * this is the value of its "label" attribute. * * @return the label */ virtual QString GetLabel() const = 0; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ virtual bool IsPredefined() const = 0; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ virtual QStringList GetCategoryPath() const = 0; virtual QStringList GetKeywordReferences() const = 0; }; } #endif /*BERRYIPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h index 9a99615885..3579329f94 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h @@ -1,106 +1,105 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIVIEWDESCRIPTOR_H_ #define BERRYIVIEWDESCRIPTOR_H_ #include #include "berryIWorkbenchPartDescriptor.h" #include "berryIViewPart.h" #include #include -#include "berryImageDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * This is a view descriptor. It provides a "description" of a given * given view so that the view can later be constructed. *

* The view registry provides facilities to map from an extension * to a IViewDescriptor. *

*

* This interface is not intended to be implemented by clients. *

* * @see org.blueberry.ui.IViewRegistry */ struct BERRY_UI_QT IViewDescriptor : public IWorkbenchPartDescriptor, public IAdaptable { berryObjectMacro(berry::IViewDescriptor) ~IViewDescriptor(); /** * Creates an instance of the view defined in the descriptor. * * @return the view part * @throws CoreException thrown if there is a problem creating the part */ virtual IViewPart::Pointer CreateView() = 0; virtual QStringList GetKeywordReferences() const = 0; /** * Returns an array of strings that represent * view's category path. This array will be used * for hierarchical presentation of the * view in places like submenus. * @return array of category tokens or null if not specified. */ virtual QStringList GetCategoryPath() const = 0; /** * Returns the description of this view. * * @return the description */ virtual QString GetDescription() const = 0; /** * Returns the descriptor for the icon to show for this view. */ - virtual SmartPointer GetImageDescriptor() const = 0; + virtual QIcon GetImageDescriptor() const = 0; /** * Returns whether this view allows multiple instances. * * @return whether this view allows multiple instances */ virtual bool GetAllowMultiple() const = 0; /** * Returns whether this view can be restored upon workbench restart. * * @return whether whether this view can be restored upon workbench restart */ virtual bool IsRestorable() const = 0; virtual bool operator==(const Object*) const = 0; }; } #endif /*BERRYIVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h index fb9327fe28..74a07dc062 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h @@ -1,270 +1,270 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef IWORKBENCHPART_H_ #define IWORKBENCHPART_H_ #include #include "berryIPropertyChangeListener.h" #include namespace berry { struct IWorkbenchPartSite; /** * \ingroup org_blueberry_ui_qt * * A workbench part is a visual component within a workbench page. There * are two subtypes: view and editor, as defined by IViewPart and * IEditorPart. *

* A view is typically used to navigate a hierarchy of information (like the * workspace), open an editor, or display properties for the active editor. * Modifications made in a view are saved immediately. *

* An editor is typically used to edit or browse a document or input object. * The input is identified using an IEditorInput. Modifications made * in an editor part follow an open-save-close lifecycle model. *

* This interface may be implemented directly. For convenience, a base * implementation is defined in WorkbenchPart. *

* The lifecycle of a workbench part is as follows: *

    *
  • When a part extension is created: *
      *
    • instantiate the part
    • *
    • create a part site
    • *
    • call part.init(site)
    • *
    *
  • When a part becomes visible in the workbench: *
      *
    • add part to presentation by calling * part.createControl(parent) to create actual widgets
    • *
    • fire partOpened event to all listeners
    • *
    *
  • *
  • When a part is activated or gets focus: *
      *
    • call part.setFocus()
    • *
    • fire partActivated event to all listeners
    • *
    *
  • *
  • When a part is closed: *
      *
    • if save is needed, do save; if it fails or is canceled return
    • *
    • if part is active, deactivate part
    • *
    • fire partClosed event to all listeners
    • *
    • remove part from presentation; part controls are disposed as part * of the SWT widget tree *
    • call part.dispose()
    • *
    *
  • *
*

*

* After createPartControl has been called, the implementor may * safely reference the controls created. When the part is closed * these controls will be disposed as part of an SWT composite. This * occurs before the IWorkbenchPart.dispose method is called. * If there is a need to free SWT resources the part should define a dispose * listener for its own control and free those resources from the dispose * listener. If the part invokes any method on the disposed SWT controls * after this point an SWTError will be thrown. *

*

* The last method called on IWorkbenchPart is dispose. * This signals the end of the part lifecycle. *

*

* An important point to note about this lifecycle is that following * a call to init, createControl may never be called. Thus in the dispose * method, implementors must not assume controls were created. *

*

* Workbench parts implement the IAdaptable interface; extensions * are managed by the platform's adapter manager. *

* * @see IViewPart * @see IEditorPart */ struct BERRY_UI_QT IWorkbenchPart : public virtual Object { // public IAdaptable { berryObjectMacro(berry::IWorkbenchPart) virtual ~IWorkbenchPart(); /** * The property id for getTitle, getTitleImage * and getTitleToolTip. */ //static const int PROP_TITLE = IWorkbenchPartConstants.PROP_TITLE; /** * Adds a listener for changes to properties of this workbench part. * Has no effect if an identical listener is already registered. *

* The property ids are defined in {@link IWorkbenchPartConstants}. *

* * @param listener a property listener */ virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; /** * Creates the controls for this workbench part. *

* Clients should not call this method (the workbench calls this method when * it needs to, which may be never). *

*

* For implementors this is a multi-step process: *

    *
  1. Create one or more controls within the parent.
  2. *
  3. Set the parent layout as needed.
  4. *
  5. Register any global actions with the site's IActionBars.
  6. *
  7. Register any context menus with the site.
  8. *
  9. Register a selection provider with the site, to make it available to * the workbench's ISelectionService (optional).
  10. *
*

* * @param parent the parent control */ virtual void CreatePartControl(void* parent) = 0; /** * Returns the site for this workbench part. The site can be * null while the workbench part is being initialized. After * the initialization is complete, this value must be non-null * for the remainder of the part's life cycle. * * @return The part site; this value may be null if the part * has not yet been initialized */ virtual SmartPointer GetSite() const = 0; /** * Returns the name of this part. If this value changes the part must fire a * property listener event with {@link IWorkbenchPartConstants#PROP_PART_NAME}. * * @return the name of this view, or the empty string if the name is being managed * by the workbench (not null) */ virtual QString GetPartName() const = 0; /** * Returns the content description of this part. The content description is an optional * user-readable string that describes what is currently being displayed in the part. * By default, the workbench will display the content description in a line * near the top of the view or editor. * An empty string indicates no content description * text. If this value changes the part must fire a property listener event * with {@link IWorkbenchPartConstants#PROP_CONTENT_DESCRIPTION}. * * @return the content description of this part (not null) */ virtual QString GetContentDescription() const = 0; /** * Returns the title image of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

* The title image is usually used to populate the title bar of this part's * visual container. Since this image is managed by the part itself, callers * must not dispose the returned image. *

* * @return the title image */ - virtual void* GetTitleImage() const = 0; + virtual QIcon GetTitleImage() const = 0; /** * Returns the title tool tip text of this workbench part. * An empty string result indicates no tool tip. * If this value changes the part must fire a property listener event with * PROP_TITLE. *

* The tool tip text is used to populate the title bar of this part's * visual container. *

* * @return the workbench part title tool tip (not null) */ virtual QString GetTitleToolTip() const = 0; /** * Removes the given property listener from this workbench part. * Has no affect if an identical listener is not registered. * * @param listener a property listener */ virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; /** * Return the value for the arbitrary property key, or null. * * @param key * the arbitrary property. Must not be null. * @return the property value, or null. */ virtual QString GetPartProperty(const QString& key) const = 0; /** * Set an arbitrary property on the part. It is the implementor's * responsibility to fire the corresponding PropertyChangeEvent. *

* A default implementation has been added to WorkbenchPart. *

* * @param key * the arbitrary property. Must not be null. * @param value * the property value. A null value will remove * that property. */ virtual void SetPartProperty(const QString& key, const QString& value) = 0; /** * Return an unmodifiable map of the arbitrary properties. This method can * be used to save the properties during workbench save/restore. * * @return A Map of the properties. Must not be null. */ virtual const QHash& GetPartProperties() const = 0; /** * Asks this part to take focus within the workbench. *

* Clients should not call this method (the workbench calls this method at * appropriate times). To have the workbench activate a part, use * IWorkbenchPage.activate(IWorkbenchPart) instead. *

*/ virtual void SetFocus() = 0; }; } // namespace berry #endif /*IWORKBENCHPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h index cb1abba10d..46f1ba7532 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h @@ -1,71 +1,68 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIWORKBENCHPARTDESCRIPTOR_H_ #define BERRYIWORKBENCHPARTDESCRIPTOR_H_ #include #include #include -#include "berryImageDescriptor.h" - - namespace berry { /** * \ingroup org_blueberry_ui_qt * * Description of a workbench part. The part descriptor contains * the information needed to create part instances. *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IWorkbenchPartDescriptor : public virtual Object { berryObjectMacro(berry::IWorkbenchPartDescriptor) /** * Returns the part id. * * @return the id of the part */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image for this part. * * @return the descriptor of the image to display next to this part */ - virtual SmartPointer GetImageDescriptor() const = 0; + virtual QIcon GetImageDescriptor() const = 0; /** * Returns the label to show for this part. * * @return the part label */ virtual QString GetLabel() const = 0; virtual ~IWorkbenchPartDescriptor(); }; } // namespace berry #endif /*BERRYIWORKBENCHPARTDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h index 5ac92dc8ed..bc2ab25bd3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h @@ -1,152 +1,142 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIWORKBENCHPARTREFERENCE_H_ #define BERRYIWORKBENCHPARTREFERENCE_H_ #include #include #include "berryIPropertyChangeListener.h" namespace berry { struct IWorkbenchPart; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_qt * * Implements a reference to a IWorkbenchPart. * The IWorkbenchPart will not be instanciated until the part * becomes visible or the API getPart is sent with true; *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IWorkbenchPartReference : public Object { berryObjectMacro(berry::IWorkbenchPartReference) ~IWorkbenchPartReference(); - /** - * Returns the IWorkbenchPart referenced by this object. - * Returns null if the editors was not instantiated or - * it failed to be restored. Tries to restore the editor - * if restore is true. - */ - virtual SmartPointer GetPart(bool restore) = 0; - - - /** - * @see IWorkbenchPart#getTitleImage - */ - virtual void* GetTitleImage() = 0; - - /** - * @see IWorkbenchPart#getTitleToolTip - */ - virtual QString GetTitleToolTip() const = 0; - - /** - * @see IWorkbenchPartSite#getId - */ - virtual QString GetId() const = 0; - - /** - * @see IWorkbenchPart#addPropertyListener - */ - virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; - - /** - * @see IWorkbenchPart#removePropertyListener - */ - virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; - - /** - * Returns the workbench page that contains this part - */ - virtual SmartPointer GetPage() const = 0; - - /** - * Returns the name of the part, as it should be shown in tabs. - * - * @return the part name - * - * @since 3.0 - */ - virtual QString GetPartName() const = 0; - - /** - * Returns the content description for the part (or the empty string if none) - * - * @return the content description for the part - * - * @since 3.0 - */ - virtual QString GetContentDescription() const = 0; - - /** - * Returns true if the part is pinned otherwise returns false. - */ - virtual bool IsPinned() const = 0; - - /** - * Returns whether the part is dirty (i.e. has unsaved changes). - * - * @return true if the part is dirty, false otherwise - * - * @since 3.2 (previously existed on IEditorReference) - */ - virtual bool IsDirty() const = 0; - - /** + /** + * Returns the IWorkbenchPart referenced by this object. + * Returns null if the editors was not instantiated or + * it failed to be restored. Tries to restore the editor + * if restore is true. + */ + virtual SmartPointer GetPart(bool restore) = 0; + + /** + * @see IWorkbenchPart#getTitleImage + */ + virtual QIcon GetTitleImage() const = 0; + + /** + * @see IWorkbenchPart#getTitleToolTip + */ + virtual QString GetTitleToolTip() const = 0; + + /** + * @see IWorkbenchPartSite#getId + */ + virtual QString GetId() const = 0; + + /** + * @see IWorkbenchPart#addPropertyListener + */ + virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; + + /** + * @see IWorkbenchPart#removePropertyListener + */ + virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; + + /** + * Returns the workbench page that contains this part + */ + virtual SmartPointer GetPage() const = 0; + + /** + * Returns the name of the part, as it should be shown in tabs. + * + * @return the part name + */ + virtual QString GetPartName() const = 0; + + /** + * Returns the content description for the part (or the empty string if none) + * + * @return the content description for the part + */ + virtual QString GetContentDescription() const = 0; + + /** + * Returns true if the part is pinned otherwise returns false. + */ + virtual bool IsPinned() const = 0; + + /** + * Returns whether the part is dirty (i.e. has unsaved changes). + * + * @return true if the part is dirty, false otherwise + */ + virtual bool IsDirty() const = 0; + + /** * Return an arbitrary property from the reference. If the part has been * instantiated, it just delegates to the part. If not, then it looks in its * own cache of properties. If the property is not available or the part has * never been instantiated, it can return null. * * @param key * The property to return. Must not be null. * @return The String property, or null. - * @since 3.3 */ - virtual QString GetPartProperty(const QString& key) const = 0; + virtual QString GetPartProperty(const QString& key) const = 0; - /** + /** * Add a listener for changes in the arbitrary properties set. * * @param listener * Must not be null. - * @since 3.3 */ - //virtual void addPartPropertyListener(IPropertyChangeListener listener) = 0; + //virtual void addPartPropertyListener(IPropertyChangeListener listener) = 0; - /** + /** * Remove a listener for changes in the arbitrary properties set. * * @param listener * Must not be null. - * @since 3.3 */ - //virtual void removePartPropertyListener(IPropertyChangeListener listener) = 0; + //virtual void removePartPropertyListener(IPropertyChangeListener listener) = 0; }; } // namespace berry #endif /*BERRYIWORKBENCHPARTREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.cpp deleted file mode 100644 index 1dd23c8151..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "tweaklets/berryImageTweaklet.h" - -#include "berryImageDescriptor.h" - -namespace berry { - -ImageDescriptor::Pointer ImageDescriptor::CreateFromFile(const QString& filename, const QString& pluginid) -{ - return Tweaklets::Get(ImageTweaklet::KEY)->CreateFromFile(filename, pluginid); -} - -ImageDescriptor::Pointer ImageDescriptor::CreateFromImage(void* img) -{ - return Tweaklets::Get(ImageTweaklet::KEY)->CreateFromImage(img); -} - -ImageDescriptor::Pointer ImageDescriptor::GetMissingImageDescriptor() -{ - return Tweaklets::Get(ImageTweaklet::KEY)->GetMissingImageDescriptor(); -} - -ImageDescriptor::ImageDescriptor() -{ - -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.h deleted file mode 100644 index 416bab4ac4..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryImageDescriptor.h +++ /dev/null @@ -1,106 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYIIMAGEDESCRIPTOR_H_ -#define BERRYIIMAGEDESCRIPTOR_H_ - -#include -#include - -#include - -namespace berry { - -/** - * An image descriptor is an object that knows how to create - * an image. Caching of images and resource management must be done - * in GUI toolkit specific classes. An image descriptor - * is intended to be a lightweight representation of an image. - *

- * To get an Image from an ImageDescriptor, the method - * CreateImage() must be called. When the caller is done with an image obtained from CreateImage, - * they must call DestroyImage() to give the GUI toolkit a chance to cleanup resources. - *

- * - * @see org.eclipse.swt.graphics.Image - */ -struct BERRY_UI_QT ImageDescriptor : public Object { - - berryObjectMacro(ImageDescriptor); - - /** - * Returns a possibly cached image for this image descriptor. The - * returned image must be explicitly disposed by calling DestroyImage(). - * The image will not be automatically garbage collected. In the event - * of an error, a default image is returned if - * returnMissingImageOnError is true, otherwise - * 0 is returned. - *

- * Note: Even if returnMissingImageOnError is true, it is - * still possible for this method to return null in extreme - * cases, for example if the underlying OS/GUI toolkit runs out of image handles. - *

- * - * @param returnMissingImageOnError - * flag that determines if a default image is returned on error - * @return the image or 0 if the image could not be - * created - */ - virtual void* CreateImage(bool returnMissingImageOnError = true) = 0; - - virtual void DestroyImage(void* img) = 0; - - virtual bool operator==(const Object* o) const = 0; - - /** - * Creates and returns a new image descriptor from a file. If you specify pluginid, the - * given filename is interpreted relative to the plugins base directory. If no pluginid - * is given and filename is a relative path, the result is undefined. - * - * @param filename the file name. - * @param pluginid the plugin id of the plugin which contains the file - * @return a new image descriptor - */ - static Pointer CreateFromFile(const QString& filename, const QString& pluginid = ""); - - /** - * Creates and returns a new image descriptor for the given image. Note - * that disposing the original Image will cause the descriptor to become invalid. - * - * @since 3.1 - * - * @param img image to create - * @return a newly created image descriptor - */ - static Pointer CreateFromImage(void* img); - - /** - * Returns the shared image descriptor for a missing image. - * - * @return the missing image descriptor - */ - static Pointer GetMissingImageDescriptor(); - - -protected: - ImageDescriptor(); -}; - -} - - -#endif /* BERRYIIMAGEDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h index f2474129fa..235f7411f4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h @@ -1,287 +1,286 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYSAVEABLE_H_ #define BERRYSAVEABLE_H_ #include #include #include #include -#include "berryImageDescriptor.h" namespace berry { struct IWorkbenchPage; struct IWorkbenchPart; /** * A Saveable represents a unit of saveability, e.g. an editable * subset of the underlying domain model that may contain unsaved changes. * Different workbench parts (editors and views) may present the same saveables * in different ways. This interface allows the workbench to provide more * appropriate handling of operations such as saving and closing workbench * parts. For example, if two editors sharing the same saveable with unsaved * changes are closed simultaneously, the user is only prompted to save the * changes once for the shared saveable, rather than once for each editor. *

* Workbench parts that work in terms of saveables should implement * {@link ISaveablesSource}. *

* * @see ISaveablesSource */ class BERRY_UI_QT Saveable : /*public InternalSaveable*/ public virtual Object, public IAdaptable { public: berryObjectMacro(Saveable) private: //Cursor waitCursor; //Cursor originalCursor; public: typedef QSet Set; /** * Attempts to show this saveable in the given page and returns * true on success. The default implementation does nothing * and returns false. * * @param page * the workbench page in which to show this saveable * @return true if this saveable is now visible to the user * @since 3.3 */ virtual bool Show(SmartPointer page); /** * Returns the name of this saveable for display purposes. * * @return the model's name; never null. */ virtual QString GetName() const = 0; /** * Returns the tool tip text for this saveable. This text is used to * differentiate between two inputs with the same name. For instance, * MyClass.java in folder X and MyClass.java in folder Y. The format of the * text varies between input types. * * @return the tool tip text; never null */ virtual QString GetToolTipText() const = 0; /** * Returns the image descriptor for this saveable. * * @return the image descriptor for this model; may be null * if there is no image */ - virtual SmartPointer GetImageDescriptor() const = 0; + virtual QIcon GetImageDescriptor() const = 0; /** * Saves the contents of this saveable. *

* If the save is cancelled through user action, or for any other reason, * the part should invoke setCancelled on the * IProgressMonitor to inform the caller. *

*

* This method is long-running; progress and cancellation are provided by * the given progress monitor. *

* * @param monitor * the progress monitor * @throws CoreException * if the save fails; it is the caller's responsibility to * report the failure to the user */ virtual void DoSave(/*IProgressMonitor monitor*/) = 0; /** * Returns whether the contents of this saveable have changed since the last * save operation. *

* Note: this method is called frequently, for example by actions to * determine their enabled status. *

* * @return true if the contents have been modified and need * saving, and false if they have not changed since * the last save */ virtual bool IsDirty() const = 0; /** * Clients must implement equals and hashCode as defined in * {@link Object#equals(Object)} and {@link Object#hashCode()}. Two * saveables should be equal if their dirty state is shared, and saving one * will save the other. If two saveables are equal, their names, tooltips, * and images should be the same because only one of them will be shown when * prompting the user to save. * * @param object * @return true if this Saveable is equal to the given object */ virtual bool operator<(const Object* object) const = 0; /** * Clients must implement equals and hashCode as defined in * {@link Object#equals(Object)} and {@link Object#hashCode()}. Two * saveables should be equal if their dirty state is shared, and saving one * will save the other. If two saveables are equal, their hash codes MUST be * the same, and their names, tooltips, and images should be the same * because only one of them will be shown when prompting the user to save. *

* IMPORTANT: Implementers should ensure that the hashCode returned is * sufficiently unique so as not to collide with hashCodes returned by other * implementations. It is suggested that the defining plug-in's ID be used * as part of the returned hashCode, as in the following example: *

* *
    *     int PRIME = 31;
    *     int hash = ...; // compute the "normal" hash code, e.g. based on some identifier unique within the defining plug-in
    *     return hash * PRIME + MY_PLUGIN_ID.hashCode();
    * 
* * @return a hash code */ virtual uint HashCode() const = 0; /** * Saves this saveable, or prepares this saveable for a background save * operation. Returns null if this saveable has been successfully saved, or * a job runnable that needs to be run to complete the save in the * background. This method is called in the UI thread. If this saveable * supports saving in the background, it should do only minimal work. * However, since the job runnable returned by this method (if any) will not * run on the UI thread, this method should copy any state that can only be * accessed from the UI thread so that the job runnable will be able to * access it. *

* The supplied shell provider can be used from within this method and from * within the job runnable for the purpose of parenting dialogs. Care should * be taken not to open dialogs gratuitously and only if user input is * required for cases where the save cannot otherwise proceed - note that in * any given save operation, many saveable objects may be saved at the same * time. In particular, errors should be signaled by throwing an exception, * or if an error occurs while running the job runnable, an error status * should be returned. *

*

* If the foreground part of the save is cancelled through user action, or * for any other reason, the part should invoke setCancelled * on the IProgressMonitor to inform the caller. If the * background part of the save is cancelled, the job should return a * {@link IStatus#CANCEL} status. *

*

* This method is long-running; progress and cancellation are provided by * the given progress monitor. *

*

* The default implementation of this method calls * {@link #doSave(IProgressMonitor)} and returns null. *

* * @param monitor * a progress monitor used for reporting progress and * cancellation * @param shellProvider * an object that can provide a shell for parenting dialogs * @return null if this saveable has been saved successfully, * or a job runnable that needs to be run to complete the save in * the background. * * @since 3.3 */ //TODO Saveable IJobRunnable, IProgressMonitor, and IShellProvider // virtual /*IJobRunnable*/void DoSave(/*IProgressMonitor monitor, // IShellProvider shellProvider*/); /** * Disables the UI of the given parts containing this saveable if necessary. * This method is not intended to be called by clients. A corresponding call * to *

* Saveables that can be saved in the background should ensure that the user * cannot make changes to their data from the UI, for example by disabling * controls, unless they are prepared to handle this case. This method is * called on the UI thread after a job runnable has been returned from * {@link #doSave(IProgressMonitor, IShellProvider)} and before * spinning the event loop. The closing flag indicates that * this saveable is currently being saved in response to closing a workbench * part, in which case further changes to this saveable through the UI must * be prevented. *

*

* The default implementation calls setEnabled(false) on the given parts' * composites. *

* * @param parts * the workbench parts containing this saveable * @param closing * a boolean flag indicating whether the save was triggered by a * request to close a workbench part, and all of the given parts * will be closed after the save operation finishes successfully. * * @since 3.3 */ virtual void DisableUI(const QList >& parts, bool closing); /** * Enables the UI of the given parts containing this saveable after a * background save operation has finished. This method is not intended to be * called by clients. *

* The default implementation calls setEnabled(true) on the given parts' * composites. *

* * @param parts * the workbench parts containing this saveable * * @since 3.3 */ virtual void EnableUI(QList >& parts); protected: /** * This implementation of {@link IAdaptable#GetAdapterImpl(const std::type_info&)} returns * null. Subclasses may override. This allows two unrelated * subclasses of Saveable to implement {@link #equals(Object)} and * {@link #hashCode()} based on an underlying implementation class that is * shared by both Saveable subclasses. * * @since 3.3 */ virtual Object* GetAdapter(const QString& adapter); }; } #endif /* BERRYSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.cpp index 044c84b2e9..e19eb50797 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.cpp @@ -1,64 +1,62 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewPart.h" -#include "berryImageDescriptor.h" - #include namespace berry { ViewPart::ViewPart() { } void ViewPart::Init(IViewSite::Pointer site, IMemento::Pointer /*memento*/) { /* * Initializes this view with the given view site. A memento is passed to * the view which contains a snapshot of the views state from a previous * session. Where possible, the view should try to recreate that state * within the part controls. *

* This implementation will ignore the memento and initialize the view in * a fresh state. Subclasses may override the implementation to perform any * state restoration as needed. */ this->SetSite(site); } void ViewPart::SaveState(IMemento::Pointer /*memento*/) { // do nothing } void ViewPart::CheckSite(IWorkbenchPartSite::Pointer site) { WorkbenchPart::CheckSite(site); if (site.Cast().IsNull()) throw Poco::AssertionViolationException("The site for a view must be an IViewSite"); //$NON-NLS-1$ } IViewSite::Pointer ViewPart::GetViewSite() { return this->GetSite().Cast(); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp index eabc3d183a..36fe6630ae 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.cpp @@ -1,313 +1,290 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchPart.h" #include "berryIWorkbenchPartConstants.h" -#include "berryImageDescriptor.h" #include #include #include #include "internal/berryWorkbenchPlugin.h" #include #include namespace berry { class PropChangedRunnable : public SafeRunnable { public: berryObjectMacro(PropChangedRunnable) IPropertyChangeListener::Events::EventType::AbstractDelegate* delegate; PropChangedRunnable(PropertyChangeEvent::Pointer event) : event(event) {} void Run() { delegate->Execute(event); } private: PropertyChangeEvent::Pointer event; }; WorkbenchPart::~WorkbenchPart() { - if (m_TitleImage && m_ImageDescriptor) - m_ImageDescriptor->DestroyImage(m_TitleImage); } WorkbenchPart::WorkbenchPart() :m_Title(""), - m_TitleImage(0), m_ToolTip(""), m_PartName(""), m_ContentDescription("") { } void WorkbenchPart::InternalSetContentDescription( const QString& description) { //assert(description != 0) //Do not send changes if they are the same if (this->m_ContentDescription == description) { return; } this->m_ContentDescription = description; this->FirePropertyChange(IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION); } void WorkbenchPart::InternalSetPartName(const QString& partName) { //partName = Util.safeString(partName); //assert(partName != 0); //Do not send changes if they are the same if (this->m_PartName == partName) { return; } this->m_PartName = partName; this->FirePropertyChange(IWorkbenchPartConstants::PROP_PART_NAME); } // IConfigurationElement* GetConfigurationElement() // { // return m_ConfigElement; // } // protected Image getDefaultImage() { // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); // } void WorkbenchPart::SetSite(IWorkbenchPartSite::Pointer site) { this->CheckSite(site); this->m_PartSite = site; } void WorkbenchPart::CheckSite(IWorkbenchPartSite::Pointer /*site*/) { // do nothing } -void WorkbenchPart::SetTitleImage(void* titleImage) +void WorkbenchPart::SetTitleImage(const QIcon& titleImage) { //assert(titleImage == 0 || !titleImage.isDisposed()); //Do not send changes if they are the same - if (this->m_TitleImage == titleImage) + if (this->m_TitleImage.cacheKey() == titleImage.cacheKey()) { return; } - m_ImageDescriptor->DestroyImage(m_TitleImage); this->m_TitleImage = titleImage; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); - - if (m_ImageDescriptor) { - //JFaceResources.getResources().destroyImage(imageDescriptor); - m_ImageDescriptor = 0; - } } void WorkbenchPart::SetTitleToolTip(const QString& toolTip) { //toolTip = Util.safeString(toolTip); //Do not send changes if they are the same if (this->m_ToolTip == toolTip) { return; } this->m_ToolTip = toolTip; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void WorkbenchPart::SetPartName(const QString& partName) { InternalSetPartName(partName); //setDefaultTitle(); } void WorkbenchPart::SetContentDescription(const QString& description) { InternalSetContentDescription(description); //setDefaultTitle(); } void WorkbenchPart::FirePropertyChanged(const QString& key, const QString& oldValue, const QString& newValue) { ObjectString::Pointer objOldVal(new ObjectString(oldValue)); ObjectString::Pointer objNewVal(new ObjectString(newValue)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, key, objOldVal, objNewVal)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = partChangeEvents.propertyChange.GetListeners(); for (ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } void WorkbenchPart::FirePropertyChange(int propertyId) { ObjectInt::Pointer val(new ObjectInt(propertyId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = partChangeEvents.propertyChange.GetListeners(); for (ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } void WorkbenchPart::AddPropertyListener(IPropertyChangeListener* l) { partChangeEvents.AddListener(l); } void WorkbenchPart::RemovePropertyListener(IPropertyChangeListener* l) { partChangeEvents.RemoveListener(l); } void WorkbenchPart::SetPartProperty(const QString& key, const QString& value) { QHash::iterator iter = partProperties.find(key); QString oldValue; if (iter != partProperties.end()) oldValue = iter.value(); if (value == "") { partProperties.remove(key); } else { partProperties.insert(key, value); } this->FirePropertyChanged(key, oldValue, value); } QString WorkbenchPart::GetPartProperty(const QString& key) const { QHash::const_iterator itr = partProperties.find(key); if (itr == partProperties.end()) return ""; return itr.value(); } const QHash &WorkbenchPart::GetPartProperties() const { return partProperties; } IWorkbenchPartSite::Pointer WorkbenchPart::GetSite() const { return this->m_PartSite; } QString WorkbenchPart::GetPartName() const { return this->m_PartName; } QString WorkbenchPart::GetContentDescription() const { return this->m_ContentDescription; } -void* WorkbenchPart::GetTitleImage() const +QIcon WorkbenchPart::GetTitleImage() const { - if (this->m_TitleImage != 0) - { - return this->m_TitleImage; - } - - return 0; + return this->m_TitleImage; //return GetDefaultImage(); } QString WorkbenchPart::GetTitleToolTip() const { return this->m_ToolTip; } void WorkbenchPart::SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& /*propertyName*/, const Object::Pointer& /*data*/) { // Save config element. m_ConfigElement = cfig; // Part name and title. m_PartName = cfig->GetAttribute("name"); m_Title = m_PartName; // Icon. QString strIcon = cfig->GetAttribute("icon"); if (strIcon.isEmpty()) { return; } - m_ImageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( + m_TitleImage = AbstractUICTKPlugin::ImageDescriptorFromPlugin( m_ConfigElement->GetContributor()->GetName(), strIcon); - - if (!m_ImageDescriptor) - { - return; - } - - //titleImage = JFaceResources.getResources().createImageWithDefault(imageDescriptor); - m_TitleImage = m_ImageDescriptor->CreateImage(); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h index 3d82c13103..10b11760e0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h @@ -1,257 +1,256 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __BERRY_WORKBENCH_PART_H__ #define __BERRY_WORKBENCH_PART_H__ #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPartSite.h" #include #include -#include "berryImageDescriptor.h" +#include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Abstract base implementation of all workbench parts. *

* This class is not intended to be subclassed by clients outside this * package; clients should instead subclass ViewPart or * EditorPart. *

* * @see org.blueberry.ui.part.ViewPart * @see org.blueberry.ui.part.EditorPart * @noextend This class is not intended to be subclassed by clients. */ class BERRY_UI_QT WorkbenchPart : public QObject, public virtual IWorkbenchPart, public IExecutableExtension { Q_OBJECT Q_INTERFACES(berry::IExecutableExtension); public: berryObjectMacro(WorkbenchPart) ~WorkbenchPart(); private: QString m_Title; - SmartPointer m_ImageDescriptor; - void* m_TitleImage; + QIcon m_TitleImage; QString m_ToolTip; IConfigurationElement::Pointer m_ConfigElement; IWorkbenchPartSite::Pointer m_PartSite; QString m_PartName; QString m_ContentDescription; QHash partProperties; IPropertyChangeListener::Events partChangeEvents; void InternalSetContentDescription(const QString& description); void InternalSetPartName(const QString& partName); protected: WorkbenchPart(); /** * Returns the configuration element for this part. The configuration element * comes from the plug-in registry entry for the extension defining this part. * * @return the configuration element for this part */ IConfigurationElement::Pointer GetConfigurationElement() const { return m_ConfigElement; } /** * Returns the default title image. * * @return the default image */ // protected Image getDefaultImage() { // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); // } /** * Sets the part site. *

* Subclasses must invoke this method from IEditorPart.init * and IViewPart.init. * * @param site the workbench part site */ void SetSite(IWorkbenchPartSite::Pointer site); /** * Checks that the given site is valid for this type of part. * The default implementation does nothing. * * @param site the site to check */ virtual void CheckSite(IWorkbenchPartSite::Pointer site); /** * Sets or clears the title image of this part. * * @param titleImage the title image, or null to clear */ - virtual void SetTitleImage(void* titleImage); + virtual void SetTitleImage(const QIcon& titleImage); /** * Sets or clears the title tool tip text of this part. Clients should * call this method instead of overriding getTitleToolTip * * @param toolTip the new tool tip text, or null to clear */ virtual void SetTitleToolTip(const QString& toolTip); /** * Sets the name of this part. The name will be shown in the tab area for * the part. Clients should call this method instead of overriding getPartName. * Setting this to the empty string will cause a default part name to be used. * * @param partName the part name, as it should be displayed in tabs. */ virtual void SetPartName(const QString& partName); /** * Sets the content description for this part. The content description is typically * a short string describing the current contents of the part. Setting this to the * empty string will cause a default content description to be used. Clients should * call this method instead of overriding getContentDescription(). For views, the * content description is shown (by default) in a line near the top of the view. For * editors, the content description is shown beside the part name when showing a * list of editors. If the editor is open on a file, this typically contains the path * to the input file, without the filename or trailing slash. * * @param description the content description */ virtual void SetContentDescription(const QString& description); void FirePropertyChanged(const QString& key, const QString& oldValue, const QString& newValue); void FirePropertyChange(int propertyId); public: /* (non-Javadoc) * Method declared on IWorkbenchPart. */ void AddPropertyListener(IPropertyChangeListener* l); void RemovePropertyListener(IPropertyChangeListener* l); void SetPartProperty(const QString& key, const QString& value); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPart3#getPartProperty(java.lang.String) */ QString GetPartProperty(const QString& key) const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPart3#getPartProperties() */ const QHash& GetPartProperties() const; /** * {@inheritDoc} * The WorkbenchPart implementation of this * IExecutableExtension records the configuration element in * and internal state variable (accessible via getConfigElement). * It also loads the title image, if one is specified in the configuration element. * Subclasses may extend. * * Should not be called by clients. It is called by the core plugin when creating * this executable extension. */ void SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& propertyName, const Object::Pointer& data); /* * Creates the controls for this workbench part. *

* Subclasses must implement this method. For a detailed description of the * requirements see IWorkbenchPart *

* * @param parent the parent control * @see IWorkbenchPart */ virtual void CreatePartControl(void* parent) = 0; /* (non-Javadoc) * Asks this part to take focus within the workbench. *

* Subclasses must implement this method. For a detailed description of the * requirements see IWorkbenchPart *

* * @see IWorkbenchPart */ virtual void SetFocus() = 0; /* * Method declared on IWorkbenchPart. */ IWorkbenchPartSite::Pointer GetSite() const; /** * {@inheritDoc} *

* It is considered bad practise to overload or extend this method. * Parts should call setPartName to change their part name. *

*/ QString GetPartName() const; /** * {@inheritDoc} *

* It is considered bad practise to overload or extend this method. * Parts should call setContentDescription to change their content description. *

*/ QString GetContentDescription() const; /* (non-Javadoc) * Method declared on IWorkbenchPart. */ - void* GetTitleImage() const; + QIcon GetTitleImage() const; /* (non-Javadoc) * Gets the title tool tip text of this part. * * @return the tool tip text */ QString GetTitleToolTip() const; }; } // namespace berry #endif // __BERRY_WORKBENCH_PART_H__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h index 6e37e62f03..0e432524de 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h @@ -1,185 +1,185 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYCATEGORY_H_ #define BERRYCATEGORY_H_ #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * Category provides for hierarchical grouping of elements * registered in the registry. One extension normally defines * a category, and other reference it via its ID. *

* A category may specify its parent category in order to * achieve hierarchy. *

*/ template class Category : /*IWorkbenchAdapter*/public IAdaptable, public Object { public: berryObjectMacro(Category) typedef T ElementType; /** * Name of the miscellaneous category */ const static QString MISC_NAME; /** * Identifier of the miscellaneous category */ const static QString MISC_ID; private: QString id; QString name; QList parentPath; QList elements; IConfigurationElement::Pointer configurationElement; public: /** * Creates an instance of Category as a * miscellaneous category. */ Category(); /** * Creates an instance of Category with * an ID and label. * * @param id the unique identifier for the category * @param label the presentation label for this category */ Category(const QString& id, const QString& label); /** * Creates an instance of Category using the * information from the specified configuration element. * * @param configElement the IConfigurationElement containing * the ID, label, and optional parent category path. * @throws WorkbenchException if the ID or label is null GetImageDescriptor() const; + QIcon GetImageDescriptor() const; /** * Return the id for this category. * @return the id */ const QString& GetId() const; /** * Return the label for this category. * * @return the label */ QString GetLabel() const; /** * Return the parent path for this category. * * @return the parent path */ QList GetParentPath(); /** * Return the unparsed parent path. May be null. * * @return the unparsed parent path or null */ QString GetRawParentPath() const; /** * Return the root path for this category. * * @return the root path */ QString GetRootPath(); /** * Return the elements contained in this category. * * @return the elements */ const QList& GetElements() const; /** * Return whether a given object exists in this category. * * @param o the object to search for * @return whether the object is in this category */ bool HasElement(const ElementType& o) const; /** * Return whether this category has child elements. * * @return whether this category has child elements */ bool HasElements() const; /* (non-Javadoc) * @see org.blueberry.ui.model.IWorkbenchAdapter#getParent(java.lang.Object) */ ElementType* GetParent(const ElementType& o); /** * Clear all elements from this category. * */ void Clear(); protected: /* (non-Javadoc) * Method declared on IAdaptable. */ Object* GetAdapter(const QString& adapter); }; } // namespace berry #include "berryCategory.txx" #endif /*BERRYCATEGORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp index f22f2e62d5..91b5f4140f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp @@ -1,123 +1,117 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryDefaultSaveable.h" #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPage.h" #include "berryUIException.h" -#include "berryImageDescriptor.h" + +#include namespace berry { DefaultSaveable::DefaultSaveable(IWorkbenchPart::Pointer _part) : part(_part) { } void DefaultSaveable::DoSave(/*IProgressMonitor monitor*/) { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { _part.Cast ()->DoSave(/*monitor*/); } } QString DefaultSaveable::GetName() const { return part.Lock()->GetPartName(); } -ImageDescriptor::Pointer DefaultSaveable::GetImageDescriptor() const +QIcon DefaultSaveable::GetImageDescriptor() const { - //TODO DefaultSaveable GetImageDescriptor - // Image image = part.getTitleImage(); - // if (image == null) - // { - // return null; - // } - // return ImageDescriptor.createFromImage(image); - return ImageDescriptor::Pointer(0); + return part.Lock()->GetTitleImage(); } QString DefaultSaveable::GetToolTipText() const { return part.Lock()->GetTitleToolTip(); } bool DefaultSaveable::IsDirty() const { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { return _part.Cast ()->IsDirty(); } return false; } uint DefaultSaveable::HashCode() const { return part.Lock()->HashCode(); } bool DefaultSaveable::operator<(const Object* obj) const { if (this == obj) return false; if (obj == 0) return true; const DefaultSaveable* other = dynamic_cast (obj); if (other == NULL) return true; if (part.Expired()) { return !other->part.Expired(); } else return part < other->part; } bool DefaultSaveable::Show(IWorkbenchPage::Pointer page) { IWorkbenchPart::Pointer _part(part); IWorkbenchPartReference::Pointer reference = page->GetReference(_part); if (reference != 0) { page->Activate(_part); return true; } if (_part.Cast () != 0) { IViewPart::Pointer viewPart = _part.Cast (); try { page->ShowView(viewPart->GetViewSite()->GetId(), viewPart->GetViewSite()->GetSecondaryId(), IWorkbenchPage::VIEW_ACTIVATE); } catch (const PartInitException& /*e*/) { return false; } return true; } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h index 5b603210a0..25f2927d62 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h @@ -1,102 +1,102 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYDEFAULTSAVEABLE_H_ #define BERRYDEFAULTSAVEABLE_H_ #include "berrySaveable.h" namespace berry { /** * A default {@link Saveable} implementation that wrappers a regular * workbench part (one that does not itself adapt to Saveable). * * @since 3.2 */ class DefaultSaveable : public Saveable { private: WeakPointer part; public: /** * Creates a new DefaultSaveable. * * @param part * the part represented by this model */ DefaultSaveable(SmartPointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#doSave(org.blueberry.core.runtime.IProgressMonitor) */ void DoSave(/*IProgressMonitor monitor*/); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getName() */ QString GetName() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getImageDescriptor() */ - SmartPointer GetImageDescriptor() const; + QIcon GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getToolTipText() */ QString GetToolTipText() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#isDirty() */ bool IsDirty() const; /* (non-Javadoc) * @see Object#HashCode() */ uint HashCode() const; /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ bool operator<(const Object* obj) const; /* (non-Javadoc) * @see org.blueberry.ui.Saveable#show(org.blueberry.ui.IWorkbenchPage) */ bool Show(SmartPointer page); }; } #endif /* BERRYDEFAULTSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.cpp index 7ea5544777..4075bb64f5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.cpp @@ -1,422 +1,421 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEditorDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" #include "berryEditorPart.h" -#include "berryImageDescriptor.h" #include "berryIContributor.h" namespace berry { const int EditorDescriptor::OPEN_INTERNAL = 0x01; const int EditorDescriptor::OPEN_INPLACE = 0x02; const int EditorDescriptor::OPEN_EXTERNAL = 0x04; EditorDescriptor::EditorDescriptor(const QString& id2, IConfigurationElement::Pointer element) : testImage(true), matchingStrategyChecked(false), openMode(0) { this->SetID(id2); this->SetConfigurationElement(element); } EditorDescriptor::EditorDescriptor() : testImage(true), matchingStrategyChecked(false), openMode(0) { } //IEditorActionBarContributor::Pointer EditorDescriptor::CreateActionBarContributor() //{ // // Handle case for predefined editor descriptors, like the // // one for IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, which // // don't have a configuration element. // if (configurationElement.IsNull()) // { // return IEditorActionBarContributor::Pointer(); // } // // // Get the contributor class name. // QString className; // if (!configurationElement->GetAttribute(IWorkbenchRegistryConstants::ATT_CONTRIBUTOR_CLASS, className)) // { // return IEditorActionBarContributor::Pointer(); // } // // // Create the contributor object. // IEditorActionBarContributor contributor; // try // { // contributor = configurationElement->CreateExecutableExtension( // IWorkbenchRegistryConstants::ATT_CONTRIBUTOR_CLASS); // } // catch (CoreException e) // { // WorkbenchPlugin::Log("Unable to create editor contributor: " + //$NON-NLS-1$ // id, e); // } // return contributor; //} QString EditorDescriptor::GetEditorClassName() const { if (configurationElement.IsNull()) { return className; } return RegistryReader::GetClassValue(configurationElement, WorkbenchRegistryConstants::ATT_CLASS); } IConfigurationElement::Pointer EditorDescriptor::GetConfigurationElement() const { return configurationElement; } IEditorPart::Pointer EditorDescriptor::CreateEditor() { IEditorPart::Pointer editorPart(configurationElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return editorPart; } QString EditorDescriptor::GetFileName() const { //if (program == null) //{ if (configurationElement.IsNull()) { return fileName; } return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_COMMAND); //} //return program.getName(); } QString EditorDescriptor::GetId() const { //if (program == null) //{ if (configurationElement.IsNull()) { return id; } return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); //} //return Util.safeString(program.getName()); } -SmartPointer EditorDescriptor::GetImageDescriptor() const +QIcon EditorDescriptor::GetImageDescriptor() const { if (testImage) { testImage = false; - if (!imageDesc) + if (imageDesc.isNull()) { QString imageFileName(this->GetImageFilename()); QString command(this->GetFileName()); if (!imageFileName.isEmpty() && configurationElement) { imageDesc = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configurationElement->GetContributor()->GetName(), imageFileName); } else if (!command.isEmpty()) { //imageDesc = WorkbenchImages.getImageDescriptorFromProgram( // command, 0); } } this->VerifyImage(); } return imageDesc; } void EditorDescriptor::VerifyImage() const { //TODO Editor verify image // if (!imageDesc) { // imageDesc = WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // else { // Image img = imageDesc.createImage(false); // if (img == null) { // // @issue what should be the default image? // imageDesc = WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } else { // img.dispose(); // } // } } QString EditorDescriptor::GetImageFilename() const { if (!configurationElement) { return imageFilename; } return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); } QString EditorDescriptor::GetLabel() const { //if (program == null) //{ if (configurationElement.IsNull()) { return editorName; } return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); //} //return program.getName(); } QString EditorDescriptor::GetLauncher() const { if (configurationElement.IsNull()) { return launcherName; } return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_LAUNCHER); } QString EditorDescriptor::GetPluginID() const { if (!configurationElement.IsNull()) { return configurationElement->GetContributor()->GetName(); } return pluginIdentifier; } bool EditorDescriptor::IsInternal() const { return this->GetOpenMode() == OPEN_INTERNAL; } bool EditorDescriptor::IsOpenInPlace() const { return this->GetOpenMode() == OPEN_INPLACE; } bool EditorDescriptor::IsOpenExternal() const { return this->GetOpenMode() == OPEN_EXTERNAL; } bool EditorDescriptor::LoadValues(IMemento::Pointer /*memento*/) { // editorName = memento.getString(IWorkbenchConstants.TAG_LABEL); // imageFilename = memento.getString(IWorkbenchConstants.TAG_IMAGE); // className = memento.getString(IWorkbenchConstants.TAG_CLASS); // launcherName = memento.getString(IWorkbenchConstants.TAG_LAUNCHER); // fileName = memento.getString(IWorkbenchConstants.TAG_FILE); // id = Util.safeString(memento.getString(IWorkbenchConstants.TAG_ID)); // pluginIdentifier = memento.getString(IWorkbenchConstants.TAG_PLUGIN); // // Integer openModeInt = memento // .getInteger(IWorkbenchConstants.TAG_OPEN_MODE); // if (openModeInt != null) // { // openMode = openModeInt.intValue(); // } // else // { // // legacy: handle the older attribute names, needed to allow reading of pre-3.0-RCP workspaces // boolean internal = new Boolean(memento // .getString(IWorkbenchConstants.TAG_INTERNAL)) // .booleanValue(); // boolean openInPlace = new Boolean(memento // .getString(IWorkbenchConstants.TAG_OPEN_IN_PLACE)) // .booleanValue(); // if (internal) // { // openMode = OPEN_INTERNAL; // } // else // { // if (openInPlace) // { // openMode = OPEN_INPLACE; // } // else // { // openMode = OPEN_EXTERNAL; // } // } // } // if (openMode != OPEN_EXTERNAL && openMode != OPEN_INTERNAL && openMode // != OPEN_INPLACE) // { // WorkbenchPlugin // .log("Ignoring editor descriptor with invalid openMode: " + this); //$NON-NLS-1$ // return false; // } // // String programName = memento // .getString(IWorkbenchConstants.TAG_PROGRAM_NAME); // if (programName != null) // { // this.program = findProgram(programName); // } return true; } void EditorDescriptor::SaveValues(IMemento::Pointer /*memento*/) { // memento.putString(IWorkbenchConstants.TAG_LABEL, getLabel()); // memento.putString(IWorkbenchConstants.TAG_IMAGE, getImageFilename()); // memento.putString(IWorkbenchConstants.TAG_CLASS, getEditorClassName()); // memento.putString(IWorkbenchConstants.TAG_LAUNCHER, getLauncher()); // memento.putString(IWorkbenchConstants.TAG_FILE, getFileName()); // memento.putString(IWorkbenchConstants.TAG_ID, getId()); // memento.putString(IWorkbenchConstants.TAG_PLUGIN, getPluginId()); // // memento.putInteger(IWorkbenchConstants.TAG_OPEN_MODE, getOpenMode()); // // legacy: handle the older attribute names, needed to allow reading of workspace by pre-3.0-RCP // memento.putString(IWorkbenchConstants.TAG_INTERNAL, String // .valueOf(isInternal())); // memento.putString(IWorkbenchConstants.TAG_OPEN_IN_PLACE, String // .valueOf(isOpenInPlace())); // // if (this.program != null) // { // memento.putString(IWorkbenchConstants.TAG_PROGRAM_NAME, // this.program.getName()); // } } int EditorDescriptor::GetOpenMode() const { if (configurationElement.IsNull()) { // if we've been serialized, return our serialized value return openMode; } else if (this->GetLauncher() != "") { // open using a launcer return EditorDescriptor::OPEN_EXTERNAL; } else if (this->GetFileName() != "") { // open using an external editor return EditorDescriptor::OPEN_EXTERNAL; } else if (this->GetPluginId() != "") { // open using an internal editor return EditorDescriptor::OPEN_INTERNAL; } else { return 0; // default for system editor } } void EditorDescriptor::SetClassName(const QString& newClassName) { className = newClassName; } void EditorDescriptor::SetConfigurationElement( IConfigurationElement::Pointer newConfigurationElement) { configurationElement = newConfigurationElement; } void EditorDescriptor::SetFileName(const QString& aFileName) { fileName = aFileName; } void EditorDescriptor::SetID(const QString& anID) { id = anID; } void EditorDescriptor::SetLauncher(const QString& newLauncher) { launcherName = newLauncher; } void EditorDescriptor::SetName(const QString& newName) { editorName = newName; } void EditorDescriptor::SetOpenMode(int mode) { openMode = mode; } void EditorDescriptor::SetPluginIdentifier(const QString& anID) { pluginIdentifier = anID; } QString EditorDescriptor::ToString() const { return "EditorDescriptor(id=" + this->GetId() + ", label=" + this->GetLabel() + ")"; } QString EditorDescriptor::GetLocalId() const { return this->GetId(); } QString EditorDescriptor::GetPluginId() const { return this->GetPluginID(); } IEditorMatchingStrategy::Pointer EditorDescriptor::GetEditorMatchingStrategy() { if (matchingStrategy.IsNull() && !matchingStrategyChecked) { matchingStrategyChecked = true; if (/*program == null &&*/!configurationElement.IsNull()) { QString strategy = configurationElement->GetAttribute( WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY); if (!strategy.isEmpty()) { try { matchingStrategy = configurationElement->CreateExecutableExtension< IEditorMatchingStrategy> ( WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY); } catch (const CoreException& e) { WorkbenchPlugin::Log( "Error creating editor management policy for editor id " + this->GetId(), e); } } } } return matchingStrategy; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.h index f689c55c73..ecf2175994 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorDescriptor.h @@ -1,390 +1,392 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEDITORDESCRIPTOR_H_ #define BERRYEDITORDESCRIPTOR_H_ #include "berryIEditorDescriptor.h" #include "berryIMemento.h" #include +#include + namespace berry { struct IEditorPart; /** * \ingroup org_blueberry_ui_internal * * @see IEditorDescriptor */ class BERRY_UI_QT EditorDescriptor : public IEditorDescriptor { //, Serializable, IPluginContribution { public: berryObjectMacro(EditorDescriptor); // @issue the following constants need not be public; see bug 47600 /** * Open internal constant. Value 0x01. */ static const int OPEN_INTERNAL; // = 0x01; /** * Open in place constant. Value 0x02. */ static const int OPEN_INPLACE; // = 0x02; /** * Open external constant. Value 0x04. */ static const int OPEN_EXTERNAL; // = 0x04; private: QString editorName; QString imageFilename; - mutable SmartPointer imageDesc; + mutable QIcon imageDesc; mutable bool testImage; QString className; QString launcherName; QString fileName; QString id; bool matchingStrategyChecked; IEditorMatchingStrategy::Pointer matchingStrategy; //Program program; //The id of the plugin which contributed this editor, null for external editors QString pluginIdentifier; int openMode; IConfigurationElement::Pointer configurationElement; /** * Create a new instance of an editor descriptor. Limited * to internal framework calls. * @param element * @param id2 */ /* package */ public: EditorDescriptor(const QString& id2, IConfigurationElement::Pointer element); /** * Create a new instance of an editor descriptor. Limited * to internal framework calls. */ /* package */ public: EditorDescriptor(); /** * Creates a descriptor for an external program. * * @param filename the external editor full path and filename * @return the editor descriptor */ //public: static EditorDescriptor::Pointer CreateForProgram(const QString& filename) { // if (filename == null) { // throw new IllegalArgumentException(); // } // EditorDescriptor editor = new EditorDescriptor(); // // editor.setFileName(filename); // editor.setID(filename); // editor.setOpenMode(OPEN_EXTERNAL); // // //Isolate the program name (no directory or extension) // int start = filename.lastIndexOf(File.separator); // String name; // if (start != -1) { // name = filename.substring(start + 1); // } else { // name = filename; // } // int end = name.lastIndexOf('.'); // if (end != -1) { // name = name.substring(0, end); // } // editor.setName(name); // // // get the program icon without storing it in the registry // ImageDescriptor imageDescriptor = new ProgramImageDescriptor(filename, // 0); // editor.setImageDescriptor(imageDescriptor); // // return editor; // } /** * Return the program called programName. Return null if it is not found. * @return org.blueberry.swt.program.Program */ //private: static Program FindProgram(const QString& programName) { // // Program[] programs = Program.getPrograms(); // for (int i = 0; i < programs.length; i++) { // if (programs[i].getName().equals(programName)) { // return programs[i]; // } // } // // return null; // } /** * Create the editor action bar contributor for editors of this type. * * @return the action bar contributor, or null */ //public: IEditorActionBarContributor::Pointer CreateActionBarContributor(); /** * Return the editor class name. * * @return the class name */ public: QString GetEditorClassName() const; /** * Return the configuration element used to define this editor, or null. * * @return the element or null */ public: IConfigurationElement::Pointer GetConfigurationElement() const; /** * Create an editor part based on this descriptor. * * @return the editor part * @throws CoreException thrown if there is an issue creating the editor */ public: SmartPointer CreateEditor(); /** * Return the file name of the command to execute for this editor. * * @return the file name to execute */ public: QString GetFileName() const; /** * Return the id for this editor. * * @return the id */ public: QString GetId() const; /** * Return the image descriptor describing this editor. * * @return the image descriptor */ -public: SmartPointer GetImageDescriptor() const; +public: QIcon GetImageDescriptor() const; /** * Verifies that the image descriptor generates an image. If not, the * descriptor is replaced with the default image. * * @since 3.1 */ private: void VerifyImage() const; /** * The name of the image describing this editor. * * @return the image file name */ public: QString GetImageFilename() const; /** * Return the user printable label for this editor. * * @return the label */ public: QString GetLabel() const; /** * Returns the class name of the launcher. * * @return the launcher class name */ public: QString GetLauncher() const; /** * Return the contributing plugin id. * * @return the contributing plugin id */ public: QString GetPluginID() const; /** * Get the program for the receiver if there is one. * @return Program */ //public: Program GetProgram() { // return this.program; // } /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isInternal */ public: bool IsInternal() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isOpenInPlace */ public: bool IsOpenInPlace() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isOpenExternal */ public: bool IsOpenExternal() const; /** * Load the object properties from a memento. * * @return true if the values are valid, false otherwise */ protected: bool LoadValues(IMemento::Pointer memento); /** * Save the object values in a IMemento */ protected: void SaveValues(IMemento::Pointer memento); /** * Return the open mode of this editor. * * @return the open mode of this editor * @since 3.1 */ private: int GetOpenMode() const; /** * Set the class name of an internal editor. */ /* package */public: void SetClassName(const QString& newClassName); /** * Set the configuration element which contributed this editor. */ /* package */public: void SetConfigurationElement( IConfigurationElement::Pointer newConfigurationElement); /** * Set the filename of an external editor. */ /* package */public: void SetFileName(const QString& aFileName); /** * Set the id of the editor. * For internal editors this is the id as provided in the extension point * For external editors it is path and filename of the editor */ /* package */public: void SetID(const QString& anID); /** * The Image to use to repesent this editor */ /* package */ // public : void SetImageDescriptor(ImageDescriptor desc) { // imageDesc = desc; // testImage = true; // } /** * The name of the image to use for this editor. */ /* package */ // public: void SetImageFilename(const QString& aFileName) { // imageFilename = aFileName; // } /** * Sets the new launcher class name * * @param newLauncher the new launcher */ /* package */public: void SetLauncher(const QString& newLauncher); /** * The label to show for this editor. */ /* package */public: void SetName(const QString& newName); /** * Sets the open mode of this editor descriptor. * * @param mode the open mode * * @issue this method is public as a temporary fix for bug 47600 */ public: void SetOpenMode(int mode); /** * The id of the plugin which contributed this editor, null for external editors. */ /* package */public: void SetPluginIdentifier(const QString& anID); /** * Set the receivers program. * @param newProgram */ /* package */ // public: void SetProgram(Program newProgram) { // // this.program = newProgram; // if (editorName == null) { // setName(newProgram.getName()); // } // } /** * For debugging purposes only. */ public: QString ToString() const; /* (non-Javadoc) * @see org.blueberry.ui.activities.support.IPluginContribution#getLocalId() */ public: QString GetLocalId() const; /* (non-Javadoc) * @see org.blueberry.ui.activities.support.IPluginContribution#getPluginId() */ public: QString GetPluginId() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#getEditorManagementPolicy() */ public: IEditorMatchingStrategy::Pointer GetEditorMatchingStrategy(); }; } #endif /*BERRYEDITORDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp index c0f205d6b5..eb32bd3dc4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp @@ -1,573 +1,572 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryEditorReference.h" #include "berryEditorManager.h" #include "berryEditorDescriptor.h" #include "berryEditorRegistry.h" #include "berryEditorSite.h" #include "berryEditorAreaHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryNullEditorInput.h" #include "berryPartTester.h" -#include "berryImageDescriptor.h" #include "berryPlatformUI.h" #include "berryIWorkbenchPartConstants.h" namespace berry { EditorReference::EditorReference(EditorManager* man, IEditorInput::Pointer input, EditorDescriptor::Pointer desc, IMemento::Pointer editorState) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); restoredInput = input; this->editorState = editorState; this->Init(desc->GetId(), "", desc->GetImageDescriptor(), desc->GetLabel(), ""); } EditorReference::EditorReference(EditorManager* man, IMemento::Pointer memento) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); this->editorMemento = memento; if (manager->UseIPersistableEditor()) { //editorState = editorMemento->GetChild(WorkbenchConstants::TAG_EDITOR_STATE); } else { editorState = 0; } // String id = memento.getString(IWorkbenchConstants.TAG_ID); // String title = memento.getString(IWorkbenchConstants.TAG_TITLE); // String tooltip = Util.safeString(memento // .getString(IWorkbenchConstants.TAG_TOOLTIP)); // String partName = memento // .getString(IWorkbenchConstants.TAG_PART_NAME); // // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) // { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) // { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } // For compatibility set the part name to the title if not found // if (partName.empty()) // { // partName = title; // } // Get the editor descriptor. // EditorDescriptor::Pointer desc; // if (id != null) // { // desc = getDescriptor(id); // } // // desc may be null if id is null or desc is not found, but findImage below handles this // String location = memento.getString(IWorkbenchConstants.TAG_PATH); // IPath path = location == null ? null : new Path(location); // ImageDescriptor iDesc = this.manager.findImage(desc, path); // // this.name = memento.getString(IWorkbenchConstants.TAG_NAME); // if (this.name == null) // { // this.name = title; // } // setPinned("true".equals(memento.getString(IWorkbenchConstants.TAG_PINNED))); //$NON-NLS-1$ // // IMemento inputMem = memento.getChild(IWorkbenchConstants.TAG_INPUT); // if (inputMem != null) // { // this.factoryId = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // // init(id, title, tooltip, iDesc, partName, ""); //$NON-NLS-1$ } EditorDescriptor::Pointer EditorReference::GetDescriptor() { return this->GetDescriptor(this->GetId()); } EditorDescriptor::Pointer EditorReference::GetDescriptor(const QString& id) { EditorDescriptor::Pointer desc; IEditorRegistry* reg = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); desc = reg->FindEditor(id).Cast (); return desc; } void EditorReference::InitListenersAndHandlers() { // Create a property change listener to track the "close editors automatically" // preference and show/remove the pin icon on editors // Only 1 listener will be created in the EditorManager when necessary //this->manager->CheckCreateEditorPropListener(); // Create a keyboard shortcut handler for pinning editors // Only 1 handler will be created in the EditorManager when necessary //this->manager->CheckCreatePinEditorShortcutKeyHandler(); } PartPane::Pointer EditorReference::CreatePane() { PartPane::Pointer pane( new PartPane(IWorkbenchPartReference::Pointer(this), this->manager->page)); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateEditorPane(this, // this->manager->page); } void EditorReference::PinStatusUpdated() { //firePropertyChange(IWorkbenchPart.PROP_TITLE); } QString EditorReference::GetFactoryId() { // IEditorPart editor = getEditor(false); // if (editor != null) // { // IPersistableElement persistable = editor.getEditorInput() // .getPersistable(); // if (persistable != null) // { // return persistable.getFactoryId(); // } // return null; // } // return factoryId; return ""; } QString EditorReference::ComputePartName() const { return WorkbenchPartReference::ComputePartName(); } QString EditorReference::GetName() { if (part.IsNotNull()) { return this->GetEditor(false)->GetEditorInput()->GetName(); } return name; } IEditorPart::Pointer EditorReference::GetEditor(bool restore) { return this->GetPart(restore).Cast (); } void EditorReference::SetName(const QString& name) { this->name = name; } IMemento::Pointer EditorReference::GetMemento() { return editorMemento; } IWorkbenchPage::Pointer EditorReference::GetPage() const { return IWorkbenchPage::Pointer(this->manager->page); } IEditorInput::Pointer EditorReference::GetEditorInput() { IEditorPart::Pointer part = this->GetEditor(false); if (part.IsNotNull()) { return part->GetEditorInput(); } return this->GetRestoredInput(); } IEditorInput::Pointer EditorReference::GetRestoredInput() { if (restoredInput.IsNotNull()) { return restoredInput; } // Get the input factory. // IMemento::Pointer editorMem = this->GetMemento(); // if (editorMem == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_persisted_state, getId(), getName())); // } // IMemento inputMem = editorMem // .getChild(IWorkbenchConstants.TAG_INPUT); // String factoryID = null; // if (inputMem != null) // { // factoryID = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // if (factoryID == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_input_factory_ID, getId(), getName())); // } // IAdaptable input = null; // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.CREATE_PART_INPUT)) // { // label = getName() != null ? getName() : factoryID; // } // try // { // UIStats.start(UIStats.CREATE_PART_INPUT, label); // IElementFactory factory = PlatformUI.getWorkbench() // .getElementFactory(factoryID); // if (factory == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_bad_element_factory, new Object[] // { factoryID, getId(), getName()})); // } // // // Get the input element. // input = factory.createElement(inputMem); // if (input == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_create_element_returned_null, new Object[] // { factoryID, getId(), getName()})); // } // }finally // { // UIStats.end(UIStats.CREATE_PART_INPUT, input, label); // } // if (!(input instanceof IEditorInput)) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_wrong_createElement_result, new Object[] // { factoryID, getId(), getName()})); // } // restoredInput = (IEditorInput) input; return restoredInput; } IWorkbenchPart::Pointer EditorReference::CreatePart() { if (EditorRegistry::EMPTY_EDITOR_ID == this->GetId()) { return this->GetEmptyEditor(this->GetDescriptor()); } IWorkbenchPart::Pointer result; // Try to restore the editor -- this does the real work of restoring the editor // try { result = this->CreatePartHelper().Cast (); } catch (PartInitException e) { // If unable to create the part, create an error part instead // and pass the error to the status handling facility // IStatus originalStatus = exception.getStatus(); // IStatus logStatus = StatusUtil.newStatus(originalStatus, // NLS.bind("Unable to create editor ID {0}: {1}", //$NON-NLS-1$ // getId(), originalStatus.getMessage())); // IStatus displayStatus = StatusUtil.newStatus(originalStatus, // NLS.bind(WorkbenchMessages.EditorManager_unableToCreateEditor, // originalStatus.getMessage())); WorkbenchPlugin::Log(QString("Unable to create editor ID ") + this->GetId() + ": " + e.what()); // Pass the error to the status handling facility //StatusManager.getManager().handle(logStatus); EditorDescriptor::Pointer descr = this->GetDescriptor(); QString label = this->GetId(); if (descr.IsNotNull()) label = descr->GetLabel(); IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart(label, e.what()); if (part.IsNotNull()) { IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site( new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (...) { //content.dispose(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); WorkbenchPlugin::Log("Error creating editor"); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } } return result; } void EditorReference::PropertyChanged(Object::Pointer source, int propId) { // Detect badly behaved editors that don't fire PROP_INPUT events // when they're supposed to. This branch is only needed to handle // malfunctioning editors. if (propId == IWorkbenchPartConstants::PROP_INPUT) { expectingInputChange = false; } WorkbenchPartReference::PropertyChanged(source, propId); } bool EditorReference::SetInput(IEditorInput::Pointer input) { if (part.IsNotNull()) { if (part.Cast ().IsNotNull()) { IReusableEditor::Pointer editor = part.Cast (); expectingInputChange = true; editor->SetInput(input); // If the editor never fired a PROP_INPUT event, log the fact that we've discovered // a buggy editor and fire the event for free. Firing the event for free isn't required // and cannot be relied on (it only works if the input change was triggered by this // method, and there are definitely other cases where events will still be lost), // but older versions of the workbench did this so we fire it here in the spirit // of playing nice. if (expectingInputChange) { // Log the fact that this editor is broken this->ReportMalfunction( "Editor is not firing a PROP_INPUT event in response to IReusableEditor.setInput(...)"); //$NON-NLS-1$ // Fire the property for free (can't be relied on since there are other ways the input // can change, but we do it here to be consistent with older versions of the workbench) FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT); } return editor->GetEditorInput() == input; } // Can't change the input if the editor already exists and isn't an IReusableEditor return false; } // Changing the input is trivial and always succeeds if the editor doesn't exist yet if (input != restoredInput) { restoredInput = input; //firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); } return true; } void EditorReference::ReportMalfunction(const QString& string) { if (!reportedMalfunctioningEditor) { reportedMalfunctioningEditor = true; QString errorMessage = "Problem detected with part " + this->GetId(); //$NON-NLS-1$ if (part.IsNotNull()) { errorMessage.append("(class = ").append(part->GetClassName()).append( ")"); //$NON-NLS-1$ //$NON-NLS-2$ } errorMessage += ": " + string; //$NON-NLS-1$ //StatusManager.getManager().handle(StatusUtil.newStatus(getDescriptor().getPluginId(), errorMessage, null)); BERRY_ERROR << errorMessage << std::endl; } } IEditorPart::Pointer EditorReference::CreatePartHelper() { EditorSite::Pointer site; IEditorPart::Pointer part; try { IEditorInput::Pointer editorInput = this->GetEditorInput(); // Get the editor descriptor. QString editorID = this->GetId(); EditorDescriptor::Pointer desc = this->GetDescriptor(); if (desc.IsNull()) { throw PartInitException("No editor descriptor for id " + editorID); } if (desc->IsInternal()) { // Create an editor instance. part = manager->CreatePart(desc); this->CreatePartProperties(part); } // else if (desc->GetId() == IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID) // { // // part = ComponentSupport.getSystemInPlaceEditor(); // // if (part == null) // { // throw new PartInitException(WorkbenchMessages.EditorManager_no_in_place_support); // } // } else { throw PartInitException("Invalid editor descriptor for id " + editorID); } // Create a pane for this part PartPane::Pointer pane = this->GetPane(); pane->CreateControl(manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); // Link everything up to the part reference (the part reference itself should not have // been modified until this point) site = manager->CreateSite(IEditorReference::Pointer(this), part, desc, editorInput); // if there is saved state that's appropriate, pass it on if (/*part instanceof IPersistableEditor &&*/editorState.IsNotNull()) { //part->RestoreState(editorState); } // Remember the site and the action bars (now that we've created them, we'll need to dispose // them if an exception occurs) //actionBars = (EditorActionBars) site.getActionBars(); part->CreatePartControl(pane->GetControl()); // The editor should now be fully created. Exercise its public interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave badly, it's much better // that it does so now while we can still cancel creation of the part. PartTester::TestEditor(part); return part; } catch (std::exception e) { throw PartInitException(e.what()); } } IEditorPart::Pointer EditorReference::GetEmptyEditor( EditorDescriptor::Pointer descr) { IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart("(Empty)", ""); IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site(new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (std::exception e) { //StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.what() << std::endl; return IEditorPart::Pointer(0); } this->part = part.Cast (); // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. this->RefreshFromPart(); //this->ReleaseReferences(); if (this->GetPage().Cast ()->GetActiveEditorReference() != this) { //fireInternalPropertyChange(INTERNAL_PROPERTY_OPENED); } return part; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp index 9659589fd5..b16b321cc9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp @@ -1,331 +1,333 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPerspectiveDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveRegistry.h" #include "berryStatus.h" #include "berryIContributor.h" +#include + namespace berry { PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, const QString& label, PerspectiveDescriptor::Pointer originalDescriptor) : singleton(false), fixed(false) { this->id = id; this->label = label; if (originalDescriptor != 0) { this->originalId = originalDescriptor->GetOriginalId(); this->imageDescriptor = originalDescriptor->imageDescriptor; // This perspective is based on a perspective in some bundle -- if // that // bundle goes away then I think it makes sense to treat this // perspective // the same as any other -- so store it with the original // descriptor's // bundle's list. // // It might also make sense the other way...removing the following // line // will allow the perspective to stay around when the originating // bundle // is unloaded. // // This might also have an impact on upgrade cases -- should we // really be // destroying all user customized perspectives when the older // version is // removed? // // I'm leaving this here for now since its a good example, but // wouldn't be // surprised if we ultimately decide on the opposite. // // The reason this line is important is that this is the value used // to // put the object into the UI level registry. When that bundle goes // away, // the registry will remove the entire list of objects. So if this // desc // has been put into that list -- it will go away. this->pluginId = originalDescriptor->GetPluginId(); } } PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement) : singleton(false), fixed(false) { this->configElement = configElement; this->id = id; // Sanity check. if ((this->GetId() == "") || (this->GetLabel() == "") || (this->GetFactoryClassName() == "")) { IStatus::Pointer status(new Status( IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, QString("Invalid extension (missing label, id or class name): ") + GetId())); throw CoreException(status); } } IPerspectiveFactory::Pointer PerspectiveDescriptor::CreateFactory() { // if there is an originalId, then use that descriptor instead if (originalId != "") { // Get the original descriptor to create the factory. If the // original is gone then nothing can be done. IPerspectiveDescriptor::Pointer target = dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()) ->FindPerspectiveWithId( originalId); return target == 0 ? IPerspectiveFactory::Pointer(0) : target.Cast< PerspectiveDescriptor> ()->CreateFactory(); } // otherwise try to create the executable extension if (configElement != 0) { try { IPerspectiveFactory::Pointer factory( configElement ->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return factory; } catch (const CoreException& /*e*/) { // do nothing } } return IPerspectiveFactory::Pointer(0); } void PerspectiveDescriptor::DeleteCustomDefinition() { dynamic_cast (WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry())->DeleteCustomDefinition( PerspectiveDescriptor::Pointer(this)); } QString PerspectiveDescriptor::GetDescription() const { return configElement == 0 ? description : RegistryReader::GetDescription( configElement); } void PerspectiveDescriptor::SetDescription(const QString& desc) { description = desc; } bool PerspectiveDescriptor::GetFixed() const { if (configElement == 0) return fixed; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_FIXED).compare("true", Qt::CaseInsensitive) == 0; } QStringList PerspectiveDescriptor::GetKeywordReferences() const { QStringList result; if (configElement.IsNull()) { return result; } auto keywordRefs = configElement->GetChildren("keywordReference"); for (auto keywordRefsIt = keywordRefs.begin(); keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString PerspectiveDescriptor::GetId() const { return id; } QString PerspectiveDescriptor::GetPluginId() const { return configElement == 0 ? pluginId : configElement->GetContributor()->GetName(); } -ImageDescriptor::Pointer PerspectiveDescriptor::GetImageDescriptor() const +QIcon PerspectiveDescriptor::GetImageDescriptor() const { - if (imageDescriptor) + if (!imageDescriptor.isNull()) return imageDescriptor; if (configElement) { QString icon = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); if (!icon.isEmpty()) { imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configElement->GetContributor()->GetName(), icon); } } - if (!imageDescriptor) + if (imageDescriptor.isNull()) { - imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); + imageDescriptor = AbstractUICTKPlugin::GetMissingIcon(); } return imageDescriptor; } QStringList PerspectiveDescriptor::GetCategoryPath() const { if(!categoryPath.empty()) return categoryPath; if (configElement.IsNotNull()) { QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); categoryPath = category.split('/', QString::SkipEmptyParts); } return categoryPath; } QString PerspectiveDescriptor::GetLabel() const { if (configElement == 0) return label; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString PerspectiveDescriptor::GetOriginalId() const { if (originalId == "") { return this->GetId(); } return originalId; } bool PerspectiveDescriptor::HasCustomDefinition() const { return dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry())->HasCustomDefinition( PerspectiveDescriptor::ConstPointer(this)); } bool PerspectiveDescriptor::HasDefaultFlag() const { if (configElement == 0) { return false; } return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::IsPredefined() const { return this->GetFactoryClassName() != "" && configElement != 0; } bool PerspectiveDescriptor::IsSingleton() const { if (configElement == 0) return singleton; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_SINGLETON).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::RestoreState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->GetChild( WorkbenchConstants::TAG_DESCRIPTOR)); if (childMem) { childMem->GetString(WorkbenchConstants::TAG_ID, id); childMem->GetString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); childMem->GetString(WorkbenchConstants::TAG_LABEL, label); childMem->GetString(WorkbenchConstants::TAG_CLASS, className); int singletonVal; singleton = childMem->GetInteger(WorkbenchConstants::TAG_SINGLETON, singletonVal); // Find a descriptor in the registry. IPerspectiveDescriptor::Pointer descriptor = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry()->FindPerspectiveWithId( this->GetOriginalId()); if (descriptor) { // Copy the state from the registred descriptor. imageDescriptor = descriptor->GetImageDescriptor(); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ return true; } void PerspectiveDescriptor::RevertToPredefined() { if (this->IsPredefined()) { this->DeleteCustomDefinition(); } } bool PerspectiveDescriptor::SaveState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->CreateChild( WorkbenchConstants::TAG_DESCRIPTOR)); childMem->PutString(WorkbenchConstants::TAG_ID, GetId()); if (!originalId.isEmpty()) { childMem->PutString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); } childMem->PutString(WorkbenchConstants::TAG_LABEL, GetLabel()); childMem->PutString(WorkbenchConstants::TAG_CLASS, GetFactoryClassName()); if (singleton) { childMem->PutInteger(WorkbenchConstants::TAG_SINGLETON, 1); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); return true; } IConfigurationElement::Pointer PerspectiveDescriptor::GetConfigElement() const { return configElement; } QString PerspectiveDescriptor::GetFactoryClassName() const { return configElement == 0 ? className : RegistryReader::GetClassValue( configElement, WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h index 33e52434b2..7d2f0119cf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h @@ -1,245 +1,246 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVEDESCRIPTOR_H_ #define BERRYPERSPECTIVEDESCRIPTOR_H_ #include #include "berryIPerspectiveDescriptor.h" #include "berryIPerspectiveFactory.h" #include "berryIMemento.h" #include +#include namespace berry { /** * \ingroup org_blueberry_ui_internal * * PerspectiveDescriptor. *

* A PerspectiveDesciptor has 3 states: *

*
    *
  1. It isPredefined(), in which case it was defined from an * extension point.
  2. *
  3. It isPredefined() and hasCustomFile, in * which case the user has customized a predefined perspective.
  4. *
  5. It hasCustomFile, in which case the user created a new * perspective.
  6. *
* */ class PerspectiveDescriptor : public IPerspectiveDescriptor { public: berryObjectMacro(PerspectiveDescriptor); private: QString id; QString pluginId; QString originalId; QString label; QString className; QString description; bool singleton; bool fixed; - mutable ImageDescriptor::Pointer imageDescriptor; + mutable QIcon imageDescriptor; IConfigurationElement::Pointer configElement; mutable QStringList categoryPath; /** * Create a new empty descriptor. * * @param id * the id of the new descriptor * @param label * the label of the new descriptor * @param originalDescriptor * the descriptor that this descriptor is based on */ public: PerspectiveDescriptor(const QString& id, const QString& label, PerspectiveDescriptor::Pointer originalDescriptor); /** * Create a descriptor from a config element. * * @param id * the id of the element to create * @param configElement * the element to base this perspective on * @throws CoreException * thrown if there are any missing attributes */ public: PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement); /** * Creates a factory for a predefined perspective. If the perspective is not * predefined return null. * * @return the IPerspectiveFactory or null * @throws CoreException * if the object could not be instantiated. */ public: IPerspectiveFactory::Pointer CreateFactory(); /** * Deletes the custom definition for a perspective.. */ public: void DeleteCustomDefinition(); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getDescription() */ public: QString GetDescription() const; public: void SetDescription(const QString& desc); QStringList GetKeywordReferences() const; /** * Returns whether or not this perspective is fixed. * * @return whether or not this perspective is fixed */ public: bool GetFixed() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getId() */ public: QString GetId() const; public: QString GetPluginId() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getImageDescriptor() */ - public: ImageDescriptor::Pointer GetImageDescriptor() const; + public: QIcon GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getLabel() */ public: QString GetLabel() const; /** * Return the original id of this descriptor. * * @return the original id of this descriptor */ public: QString GetOriginalId() const; /** * Returns true if this perspective has a custom definition. * * @return whether this perspective has a custom definition */ public: bool HasCustomDefinition() const; /** * Returns true if this perspective wants to be default. * * @return whether this perspective wants to be default */ public: bool HasDefaultFlag() const; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ public: bool IsPredefined() const; /** * Returns true if this perspective is a singleton. * * @return whether this perspective is a singleton */ public: bool IsSingleton() const; /** * Restore the state of a perspective from a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ public: bool RestoreState(IMemento::Pointer memento); /** * Revert to the predefined extension template. Does nothing if this * descriptor is user defined. */ public: void RevertToPredefined(); /** * Save the state of a perspective to a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ public: bool SaveState(IMemento::Pointer memento); /** * Return the configuration element used to create this perspective, if one * was used. * * @return the configuration element used to create this perspective * @since 3.0 */ public: IConfigurationElement::Pointer GetConfigElement() const; /** * Returns the factory class name for this descriptor. * * @return the factory class name for this descriptor * @since 3.1 */ public: QString GetFactoryClassName() const; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ public: QStringList GetCategoryPath() const; }; } #endif /*BERRYPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.cpp index 0c255fd5c0..be77a816cc 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.cpp @@ -1,316 +1,316 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPresentablePart.h" #include "berryIWorkbenchPartConstants.h" #include "berryPartPane.h" #include "berryWorkbenchPage.h" #include namespace berry { PresentablePart:: PropertyListenerProxy::PropertyListenerProxy(PresentablePart* p) : part(p) { } void PresentablePart:: PropertyListenerProxy::PropertyChange(const PropertyChangeEvent::Pointer& e) { if (e->GetProperty() == IWorkbenchPartConstants::INTEGER_PROPERTY) { // these are "part" events PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer(part), e->GetProperty(), e->GetOldValue(), e->GetNewValue())); part->FirePropertyChange(event); } else { part->FirePropertyChange(e); } } IPropertyChangeListener* PresentablePart::GetPropertyListenerProxy() { if (lazyPropertyListenerProxy == 0) { lazyPropertyListenerProxy.reset(new PropertyListenerProxy(this)); } return lazyPropertyListenerProxy.data(); } WorkbenchPartReference::Pointer PresentablePart::GetPartReference() const { return part->GetPartReference().Cast(); } void PresentablePart::FirePropertyChange(const PropertyChangeEvent::Pointer& event) { partPropertyChangeEvents.propertyChange(event); } void PresentablePart::FirePropertyChange(int propId) { ObjectInt::Pointer val(new ObjectInt(propId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); this->FirePropertyChange(event); } PresentablePart::PresentablePart(PartPane::Pointer part, void* /*parent*/) { enableInputs = true; enableOutputs = true; isVisible = false; isDirty = false; isBusy = false; hasViewMenu = false; this->part = part; this->GetPane()->AddPropertyListener(this->GetPropertyListenerProxy()); } PartPane::Pointer PresentablePart::GetPane() const { return part; } PresentablePart::~PresentablePart() { // Ensure that the property listener is detached (necessary to prevent leaks) this->GetPane()->RemovePropertyListener(this->GetPropertyListenerProxy()); } void PresentablePart::AddPropertyListener(IPropertyChangeListener* listener) { partPropertyChangeEvents.AddListener(listener); } void PresentablePart::RemovePropertyListener(IPropertyChangeListener* listener) { partPropertyChangeEvents.RemoveListener(listener); } void PresentablePart::SetBounds(const Rectangle& bounds) { savedBounds = bounds; if (enableInputs && part != 0) { part->SetBounds(bounds); } } void PresentablePart::SetVisible(bool isVisible) { this->isVisible = isVisible; if (enableInputs) { part->SetVisible(isVisible); } } void PresentablePart::SetFocus() { if (part != 0) { if (part->GetPage()->GetActivePart() == part->GetPartReference()->GetPart(false)) { part->SetFocus(); } else { part->RequestActivation(); } } } QString PresentablePart::GetName() const { if (enableOutputs) { return this->GetPartReference()->GetPartName(); } return name; } QString PresentablePart::GetTitle() const { return this->GetPartReference()->GetPartName(); } QString PresentablePart::GetTitleStatus() const { if (enableOutputs) { return this->GetPartReference()->GetContentDescription(); } return titleStatus; } -void* PresentablePart::GetTitleImage() +QIcon PresentablePart::GetTitleImage() { if (enableOutputs) { return this->GetPartReference()->GetTitleImage(); } // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); - return 0; + return QIcon(); } QString PresentablePart::GetTitleToolTip() const { return this->GetPartReference()->GetTitleToolTip(); } bool PresentablePart::IsDirty() const { if (enableOutputs) { return this->GetPartReference()->IsDirty(); } return isDirty; } bool PresentablePart::IsBusy() const { if (enableOutputs) { return part->IsBusy(); } return isBusy; } void* PresentablePart::GetToolBar() { if (enableOutputs) { return this->GetPane()->GetToolBar(); } return 0; } bool PresentablePart::IsCloseable() const { return part->IsCloseable(); } void* PresentablePart::GetControl() { return part->GetControl(); } void PresentablePart::EnableOutputs(bool isActive) { if (isActive == this->enableOutputs) { return; } this->enableOutputs = isActive; if (isActive) { if (isBusy != this->GetPane()->IsBusy()) { this->FirePropertyChange(PROP_BUSY); } if (isDirty != this->IsDirty()) { this->FirePropertyChange(PROP_DIRTY); } if (name != this->GetName()) { this->FirePropertyChange(PROP_PART_NAME); } if (titleStatus != this->GetTitleStatus()) { this->FirePropertyChange(PROP_CONTENT_DESCRIPTION); } if (hasViewMenu != this->GetPane()->HasViewMenu()) { this->FirePropertyChange(PROP_PANE_MENU); } // Always assume that the toolbar and title has changed (keeping track of this for real // would be too expensive) this->FirePropertyChange(PROP_TOOLBAR); this->FirePropertyChange(PROP_TITLE); this->GetPane()->AddPropertyListener(this->GetPropertyListenerProxy()); } else { this->GetPane()->RemovePropertyListener(this->GetPropertyListenerProxy()); WorkbenchPartReference::Pointer ref = this->GetPartReference(); isBusy = this->GetPane()->IsBusy(); isDirty = ref->IsDirty(); name = ref->GetPartName(); titleStatus = ref->GetContentDescription(); hasViewMenu = this->GetPane()->HasViewMenu(); this->FirePropertyChange(PROP_TITLE); this->FirePropertyChange(PROP_TOOLBAR); } } void PresentablePart::EnableInputs(bool isActive) { if (isActive == this->enableInputs) { return; } this->enableInputs = isActive; if (isActive) { if (isActive && part != 0) { part->SetBounds(savedBounds); } part->SetVisible(isVisible); } } QString PresentablePart::GetPartProperty(const QString& key) const { return this->GetPartReference()->GetPartProperty(key); } int PresentablePart::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult) { return this->GetPane()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredResult); } int PresentablePart::GetSizeFlags(bool width) { return this->GetPane()->GetSizeFlags(width); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.h index e536dcf272..9e30b854a0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentablePart.h @@ -1,266 +1,266 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPRESENTABLEPART_H_ #define BERRYPRESENTABLEPART_H_ #include "presentations/berryIPresentablePart.h" #include "berryWorkbenchPartReference.h" namespace berry { class PartPane; /** * This is a lightweight adapter that allows PartPanes to be used by a StackPresentation. All methods * either redirect directly to PartPane or do trivial type conversions. All listeners registered by * the presentation are kept here rather than registering them directly on the PartPane. This allows * us to remove all listeners registered by a presentation that has been disposed, offering some * protection against memory leaks. */ class PresentablePart: public IPresentablePart { public: - berryObjectMacro(PresentablePart); + berryObjectMacro(PresentablePart) private: SmartPointer part; /** * Local listener list -- we use this rather than registering listeners directly on the part * in order to protect against memory leaks in badly behaved presentations. */ //List listeners = new ArrayList(); // Lazily initialized. Use getPropertyListenerProxy() to access. QScopedPointer lazyPropertyListenerProxy; //ListenerList partPropertyChangeListeners = new ListenerList(); IPropertyChangeListener::Events partPropertyChangeEvents; //IPropertyChangeListener::Pointer lazyPartPropertyChangeListener; // Lazily initialized. Use getMenu() to access //IPartMenu viewMenu; // True iff the "set" methods on this object are talking to the real part (disabled // if the part is currently being managed by another presentation stack) bool enableInputs; // True iff the "get" methods are returning up-to-date info from the real part (disabled // for efficiency if the presentation is invisible) bool enableOutputs; Rectangle savedBounds; bool isVisible; // Saved state (only used when the part is inactive) QString name; QString titleStatus; bool isDirty; bool isBusy; bool hasViewMenu; struct PropertyListenerProxy: public IPropertyChangeListener { PropertyListenerProxy(PresentablePart* part); using IPropertyChangeListener::PropertyChange; void PropertyChange(const PropertyChangeEvent::Pointer& e); private: PresentablePart* part; }; friend struct PropertyListenerProxy; IPropertyChangeListener* GetPropertyListenerProxy(); WorkbenchPartReference::Pointer GetPartReference() const; protected: void FirePropertyChange(int propId); void FirePropertyChange(const PropertyChangeEvent::Pointer& event); public: /** * Constructor * * @param part */ PresentablePart(SmartPointer part, void* parent); SmartPointer GetPane() const; /** * Detach this PresentablePart from the real part. No further methods should * be invoked on this object. */ ~PresentablePart(); // void firePropertyChange(int propertyId) { // for (int i = 0; i < listeners.size(); i++) { // ((IPropertyListener) listeners.get(i)).propertyChanged(this, propertyId); // } // } void AddPropertyListener(IPropertyChangeListener* listener); void RemovePropertyListener(IPropertyChangeListener* listener); // void addPartPropertyListener(IPropertyChangeListener listener) { // partPropertyChangeListeners.add(listener); // } // // void removePartPropertyListener(IPropertyChangeListener listener) { // partPropertyChangeListeners.remove(listener); // } /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setBounds(org.blueberry.swt.graphics.Rectangle) */ void SetBounds(const Rectangle& bounds); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setVisible(boolean) */ void SetVisible(bool isVisible); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getName() */ QString GetName() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getTitle() */ QString GetTitle() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getTitleStatus() */ QString GetTitleStatus() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getTitleImage() */ - void* GetTitleImage(); + QIcon GetTitleImage(); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getTitleToolTip() */ QString GetTitleToolTip() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#isDirty() */ bool IsDirty() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#isBusy() */ bool IsBusy() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getToolBar() */ void* GetToolBar(); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getMenu() */ // IPartMenu getMenu() { // boolean hasMenu; // // if (enableOutputs) { // hasMenu = part.hasViewMenu(); // } else { // hasMenu = this.hasViewMenu; // } // // if (!hasMenu) { // return null; // } // // if (viewMenu == null) { // viewMenu = new IPartMenu() { // public void showMenu(Point location) { // part.showViewMenu(location); // } // }; // } // // return viewMenu; // } /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#isCloseable() */ bool IsCloseable() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getControl() */ void* GetControl(); void EnableOutputs(bool isActive); void EnableInputs(bool isActive); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getPartProperty(java.lang.String) */ QString GetPartProperty(const QString& key) const; /* (non-Javadoc) * @see org.blueberry.ui.ISizeProvider#computePreferredSize(boolean, int, int, int) */ int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); /* (non-Javadoc) * @see org.blueberry.ui.ISizeProvider#getSizeFlags(boolean) */ int GetSizeFlags(bool width); }; } #endif /* BERRYPRESENTABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.cpp deleted file mode 100755 index f7ccde3bc5..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "berryQtFileImageDescriptor.h" - -#include "tweaklets/berryImageTweaklet.h" - -#include - -#include -#include -#include - -namespace berry -{ - -QtFileImageDescriptor::QtFileImageDescriptor(const QString& filename, - const QString& pluginid) : - filename(filename), pluginid(pluginid) -{ - -} - -void* QtFileImageDescriptor::CreateImage(bool returnMissingImageOnError) -{ - if (pluginid.isEmpty()) - { - QFile f(filename); - if (f.open(QFile::ReadOnly)) - { - QByteArray ba = f.readAll(); - return this->CreateFromByteArray(ba); - } - else - { - BERRY_ERROR << "Could not open file: " << filename; - if (returnMissingImageOnError) - return GetMissingImageDescriptor()->CreateImage(); - - return 0; - } - } - else - { - QSharedPointer plugin(Platform::GetCTKPlugin(pluginid)); - if (!plugin) - { - if (returnMissingImageOnError) - return GetMissingImageDescriptor()->CreateImage(); - - return 0; - } - - QByteArray ba = plugin->getResource(filename); - if (ba.isEmpty() && returnMissingImageOnError) - return GetMissingImageDescriptor()->CreateImage(); - - return this->CreateFromByteArray(ba); - } -} - -void QtFileImageDescriptor::DestroyImage(void* img) -{ - const QIcon* icon = static_cast(img); - delete icon; -} - -QIcon* QtFileImageDescriptor::CreateFromByteArray(const QByteArray& ba) -{ - QPixmap pixmap; - pixmap.loadFromData(ba); - QIcon* icon = new QIcon(pixmap); - return icon; -} - -bool QtFileImageDescriptor::operator ==(const Object* o) const -{ - if (const QtFileImageDescriptor* obj = dynamic_cast(o)) - { - return this->pluginid == obj->pluginid && this->filename == obj->filename; - } - - return false; -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.h deleted file mode 100755 index 8411486291..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtFileImageDescriptor.h +++ /dev/null @@ -1,52 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYFILEIMAGEDESCRIPTOR_H_ -#define BERRYFILEIMAGEDESCRIPTOR_H_ - -#include "berryImageDescriptor.h" - -#include - -class QIcon; - -namespace berry { - -class QtFileImageDescriptor : public ImageDescriptor -{ - -private: - - const QString filename; - const QString pluginid; - - QIcon* CreateFromByteArray(const QByteArray& ba); - -public: - - QtFileImageDescriptor(const QString& filename, const QString& pluginid); - - virtual void* CreateImage(bool returnMissingImageOnError = true); - - virtual void DestroyImage(void* img); - - bool operator ==(const Object* o) const; -}; - -} - -#endif /* BERRYFILEIMAGEDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.cpp deleted file mode 100755 index 896953d03c..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "berryQtIconImageDescriptor.h" - -#include - -namespace berry { - -QtIconImageDescriptor::QtIconImageDescriptor(void* img) -: icon(static_cast(img)) -{ - -} - -QtIconImageDescriptor::~QtIconImageDescriptor() -{ - delete icon; -} - -void* QtIconImageDescriptor::CreateImage(bool returnMissingImageOnError) -{ - if (icon) return new QIcon(*icon); - - if (returnMissingImageOnError) - return GetMissingImageDescriptor()->CreateImage(); - - return 0; -} - -void QtIconImageDescriptor::DestroyImage(void* img) -{ - QIcon* i = static_cast(img); - delete i; -} - -bool QtIconImageDescriptor::operator ==(const Object* o) const -{ - if (const QtIconImageDescriptor* obj = dynamic_cast(o)) - { - return this->icon == obj->icon; - } - - return false; -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.h deleted file mode 100755 index 17df7909b0..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtIconImageDescriptor.h +++ /dev/null @@ -1,49 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYQTICONIMAGEDESCRIPTOR_H_ -#define BERRYQTICONIMAGEDESCRIPTOR_H_ - -#include - -class QIcon; - -namespace berry { - -class QtIconImageDescriptor : public ImageDescriptor -{ - -private: - - QIcon* icon; - -public: - - QtIconImageDescriptor(void* img); - ~QtIconImageDescriptor(); - - virtual void* CreateImage(bool returnMissingImageOnError = true); - - virtual void DestroyImage(void* img); - - virtual bool operator==(const Object* o) const; - -}; - -} - -#endif /* BERRYQTICONIMAGEDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.cpp deleted file mode 100755 index 99a86f9524..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "berryQtImageTweaklet.h" - -#include -#include "berryQtFileImageDescriptor.h" -#include "berryQtIconImageDescriptor.h" -#include "berryQtMissingImageDescriptor.h" - -namespace berry { - -QtImageTweaklet::QtImageTweaklet() -{ - -} - -SmartPointer QtImageTweaklet::CreateFromFile(const QString& filename, const QString& pluginid) -{ - ImageDescriptor::Pointer descriptor(new QtFileImageDescriptor(filename, pluginid)); - return descriptor; -} - -SmartPointer QtImageTweaklet::CreateFromImage(void* img) -{ - ImageDescriptor::Pointer descriptor(new QtIconImageDescriptor(img)); - return descriptor; -} - -SmartPointer QtImageTweaklet::GetMissingImageDescriptor() -{ - SmartPointer descriptor(new QtMissingImageDescriptor()); - return descriptor; -} - -void QtImageTweaklet::DestroyImage(const void* /*img*/) -{ - -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.h deleted file mode 100755 index d47cc5c1f1..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtImageTweaklet.h +++ /dev/null @@ -1,44 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYQTIMAGETWEAKLET_H_ -#define BERRYQTIMAGETWEAKLET_H_ - -#include - -namespace berry { - -class QtImageTweaklet : public QObject, public ImageTweaklet -{ - Q_OBJECT - Q_INTERFACES(berry::ImageTweaklet) - -public: - - QtImageTweaklet(); - - virtual SmartPointer CreateFromFile(const QString& filename, const QString& pluginid); - virtual SmartPointer CreateFromImage(void* img); - virtual SmartPointer GetMissingImageDescriptor(); - - virtual void DestroyImage(const void* img); - -}; - -} - -#endif /* BERRYQTIMAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.cpp deleted file mode 100755 index b8b9277638..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "berryQtMissingImageDescriptor.h" - -#include - -namespace berry { - - -void* QtMissingImageDescriptor::CreateImage(bool /*returnMissingImageOnError*/) -{ - return new QIcon(":/org.blueberry.ui.qt/icon_missing.png"); -} - -void QtMissingImageDescriptor::DestroyImage(void* img) -{ - QIcon* i = static_cast(img); - delete i; -} - -bool QtMissingImageDescriptor::operator ==(const Object* o) const -{ - return dynamic_cast(o) != 0; -} - -} // namespace - - diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.h deleted file mode 100755 index 3975d07039..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtMissingImageDescriptor.h +++ /dev/null @@ -1,44 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYQTMISSINGIMAGEDESCRIPTOR_H_ -#define BERRYQTMISSINGIMAGEDESCRIPTOR_H_ - -#include - -class QIcon; - -namespace berry { - -class QtMissingImageDescriptor : public ImageDescriptor -{ - -private: - -public: - - virtual void* CreateImage(bool returnMissingImageOnError = true); - - virtual void DestroyImage(void* img); - - virtual bool operator==(const Object* o) const; - -}; - -} - -#endif /* BERRYQTICONIMAGEDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtOpenPerspectiveAction.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtOpenPerspectiveAction.cpp index e5ff98a458..aef61e1fff 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtOpenPerspectiveAction.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtOpenPerspectiveAction.cpp @@ -1,62 +1,61 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryQtOpenPerspectiveAction.h" #include #include #include #include namespace berry { QtOpenPerspectiveAction::QtOpenPerspectiveAction( IWorkbenchWindow::Pointer window, IPerspectiveDescriptor::Pointer descr, QActionGroup* group) : QAction(0), window(window.GetPointer()) { this->setParent(group); this->setText(descr->GetLabel()); this->setToolTip(descr->GetLabel()); this->setCheckable(true); this->setIconVisibleInMenu(true); group->addAction(this); - QIcon* icon = static_cast(descr->GetImageDescriptor()->CreateImage()); - this->setIcon(*icon); - descr->GetImageDescriptor()->DestroyImage(icon); + QIcon icon = descr->GetImageDescriptor(); + this->setIcon(icon); perspectiveId = descr->GetId(); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QtOpenPerspectiveAction::Run() { try { window->GetWorkbench()->ShowPerspective(perspectiveId, IWorkbenchWindow::Pointer(window)); } catch (...) { QMessageBox::critical(0, "Opening Perspective Failed", QString("The perspective \"") + this->text() + "\" could not be opened.\nSee the log for details."); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp index 19aace919f..12fe94ca27 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp @@ -1,60 +1,59 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryQtShowViewAction.h" #include #include namespace berry { QtShowViewAction::QtShowViewAction(IWorkbenchWindow::Pointer window, IViewDescriptor::Pointer desc) : QAction(0) { this->setParent(static_cast(window->GetShell()->GetControl())); this->setText(desc->GetLabel()); this->setToolTip(desc->GetLabel()); this->setIconVisibleInMenu(true); - QIcon* icon = static_cast(desc->GetImageDescriptor()->CreateImage()); - this->setIcon(*icon); - desc->GetImageDescriptor()->DestroyImage(icon); + QIcon icon = desc->GetImageDescriptor(); + this->setIcon(icon); m_Window = window.GetPointer(); m_Desc = desc; this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QtShowViewAction::Run() { IWorkbenchPage::Pointer page = m_Window->GetActivePage(); if (page.IsNotNull()) { try { page->ShowView(m_Desc->GetId()); } catch (const PartInitException& e) { BERRY_ERROR << "Error: " << e.what(); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp index 2079319136..0a3e3aa809 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp @@ -1,164 +1,163 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include "berryRegistryReader.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" -#include "berryImageDescriptor.h" namespace { bool CompareExtensionsByContributor(const berry::IExtension::Pointer& e1, const berry::IExtension::Pointer& e2) { return e1->GetContributor()->GetName().compare(e2->GetContributor()->GetName(), Qt::CaseInsensitive) < 0; } } namespace berry { RegistryReader::RegistryReader() { } RegistryReader::~RegistryReader() { } void RegistryReader::LogError(const IConfigurationElement::Pointer& element, const QString& text) { IExtension::Pointer extension = element->GetDeclaringExtension(); QString buf = QString("Plugin ") + extension->GetContributor()->GetName() + ", extension " + extension->GetExtensionPointUniqueIdentifier(); // look for an ID if available - this should help debugging QString id = element->GetAttribute("id"); if (!id.isEmpty()) { buf.append(", id "); buf.append(id); } buf.append(": " + text); WorkbenchPlugin::Log(buf); } void RegistryReader::LogMissingAttribute( const IConfigurationElement::Pointer& element, const QString& attributeName) { RegistryReader::LogError(element, "Required attribute '" + attributeName + "' not defined"); } void RegistryReader::LogMissingElement( const IConfigurationElement::Pointer& element, const QString& elementName) { RegistryReader::LogError(element, "Required sub element '" + elementName + "' not defined"); } void RegistryReader::LogUnknownElement( const IConfigurationElement::Pointer& element) { RegistryReader::LogError(element, "Unknown extension tag found: " + element->GetName()); } QList RegistryReader::OrderExtensions( const QList& extensions) { // By default, the order is based on plugin id sorted // in ascending order. The order for a plugin providing // more than one extension for an extension point is // dependent in the order listed in the XML file. QList sortedExtension(extensions); qStableSort(sortedExtension.begin(), sortedExtension.end(), CompareExtensionsByContributor); return sortedExtension; } void RegistryReader::ReadElementChildren( const IConfigurationElement::Pointer& element) { this->ReadElements(element->GetChildren()); } void RegistryReader::ReadElements( const QList& elements) { for (int i = 0; i < elements.size(); i++) { if (!this->ReadElement(elements[i])) { RegistryReader::LogUnknownElement(elements[i]); } } } void RegistryReader::ReadExtension(const IExtension::Pointer& extension) { this->ReadElements(extension->GetConfigurationElements()); } void RegistryReader::ReadRegistry( const QString& pluginId, const QString& extensionPoint) { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint(pluginId + "." + extensionPoint); if (point == 0) { return; } QList extensions(point->GetExtensions()); extensions = this->OrderExtensions(extensions); for (int i = 0; i < extensions.size(); i++) { this->ReadExtension(extensions[i]); } } QString RegistryReader::GetDescription(const IConfigurationElement::Pointer& configElement) { QList children(configElement->GetChildren(WorkbenchRegistryConstants::TAG_DESCRIPTION)); if (children.size() >= 1) { return children[0]->GetValue(); } return ""; } QString RegistryReader::GetClassValue( const IConfigurationElement::Pointer& configElement, const QString& classAttributeName) { QString className = configElement->GetAttribute(classAttributeName); if (!className.isEmpty()) { return className; } QList candidateChildren(configElement->GetChildren(classAttributeName)); if (candidateChildren.isEmpty()) { return ""; } return candidateChildren[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp index fbceea83cf..23a64826da 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp @@ -1,633 +1,632 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berrySaveablesList.h" #include "berryWorkbenchPlugin.h" #include "berryDefaultSaveable.h" -#include "berryImageDescriptor.h" #include "berryWorkbenchPart.h" namespace berry { bool SaveablesList::AddModel(Object::Pointer source, Saveable::Pointer model) { if (model == 0) { this->LogWarning("Ignored attempt to add invalid saveable", source, model); //$NON-NLS-1$ return false; } bool result = false; Saveable::Set& modelsForSource = modelMap[source.GetPointer()]; if (modelsForSource.find(model) == modelsForSource.end()) { modelsForSource.insert(model); result = this->IncrementRefCount(modelRefCounts, model); } else { this->LogWarning("Ignored attempt to add saveable that was already registered", source, model); //$NON-NLS-1$ } return result; } bool SaveablesList::IncrementRefCount( QHash& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; if (refCount == 0) { result = true; } refCount++; return result; } bool SaveablesList::DecrementRefCount( QHash& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; poco_assert(refCount != 0); if (refCount == 1) { referenceMap.remove(key); result = true; } else { --refCount; } return result; } bool SaveablesList::RemoveModel(Object::Pointer source, Saveable::Pointer model) { bool result = false; QHash::iterator it = modelMap.find(source.GetPointer()); if (it == modelMap.end()) { this->LogWarning( "Ignored attempt to remove a saveable when no saveables were known", source, model); //$NON-NLS-1$ } else { Saveable::Set& modelsForSource = it.value(); if (modelsForSource.remove(model)) { result = this->DecrementRefCount(modelRefCounts, model); if (modelsForSource.empty()) { modelMap.remove(source.GetPointer()); } } else { this->LogWarning( "Ignored attempt to remove a saveable that was not registered", source, model); //$NON-NLS-1$ } } return result; } void SaveablesList::LogWarning(const QString& message, Object::Pointer source, Saveable::Pointer model) { // create a new exception QString text = message + "; " + "unknown saveable: " + model->GetName() + " from part: " + source->GetClassName(); // record the current stack trace to help with debugging //assertionFailedException.fillInStackTrace(); WorkbenchPlugin::Log(text); } void SaveablesList::UpdateNonPartSource(ISaveablesSource::Pointer source) { QList saveables = source->GetSaveables(); if (saveables.empty()) { nonPartSources.remove(source); } else { nonPartSources.insert(source); } } void SaveablesList::RemoveModels(Object::Pointer source, const QList& modelArray) { QList removed; for (int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->RemoveModel(source, model)) { removed.push_back(model); } } if (removed.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::AddModels(Object::Pointer source, const QList& modelArray) { QList added; for (int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->AddModel(source, model)) { added.push_back(model); } } if (added.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, added, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::FireModelLifecycleEvent( SaveablesLifecycleEvent::Pointer event) { events.lifecycleChange(event); } bool SaveablesList::PromptForSavingIfNecessary( IWorkbenchWindow::Pointer /*window*/, const Saveable::Set& /*modelsClosing*/, const QHash& /*modelsDecrementing*/, bool /*canCancel*/) { // List modelsToOptionallySave = new ArrayList(); // for (Iterator it = modelsDecrementing.keySet().iterator(); it.hasNext();) // { // Saveable modelDecrementing = (Saveable) it.next(); // if (modelDecrementing.isDirty() && !modelsClosing.contains( // modelDecrementing)) // { // modelsToOptionallySave.add(modelDecrementing); // } // } // // boolean shouldCancel = // modelsToOptionallySave.isEmpty() ? false : promptForSaving( // modelsToOptionallySave, window, window, canCancel, true); // // if (shouldCancel) // { // return true; // } // // List modelsToSave = new ArrayList(); // for (Iterator it = modelsClosing.iterator(); it.hasNext();) // { // Saveable modelClosing = (Saveable) it.next(); // if (modelClosing.isDirty()) // { // modelsToSave.add(modelClosing); // } // } // return modelsToSave.isEmpty() ? false : promptForSaving(modelsToSave, window, // window, canCancel, false); return false; } void SaveablesList::FillModelsClosing(Saveable::Set& modelsClosing, const QHash& modelsDecrementing) { for (QHash::const_iterator it = modelsDecrementing.begin(); it != modelsDecrementing.end(); ++it) { Saveable::Pointer model = it.key(); if (it.value() == modelRefCounts[model]) { modelsClosing.insert(model); } } } QList SaveablesList::GetSaveables( IWorkbenchPart::Pointer part) { if (part.Cast () != 0) { ISaveablesSource::Pointer source = part.Cast(); return source->GetSaveables(); } else if (part.Cast () != 0) { QList result; Saveable::Pointer defaultSaveable(new DefaultSaveable(part)); result.push_back(defaultSaveable); return result; } else { return QList(); } } Saveable::Set SaveablesList::GetOpenModels() { Saveable::Set allDistinctModels; for (QHash::iterator it = modelMap.begin(); it != modelMap.end(); ++it) allDistinctModels.unite(it.value()); return allDistinctModels; } void SaveablesList::HandleLifecycleEvent(const SaveablesLifecycleEvent::Pointer& event) { if (event->GetSource().Cast () == 0) { // just update the set of non-part sources. No prompting necessary. // See bug 139004. this->UpdateNonPartSource(event->GetSource().Cast()); return; } QList modelArray = event->GetSaveables(); int eventType = event->GetEventType(); if (eventType == SaveablesLifecycleEvent::POST_OPEN) { this->AddModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::PRE_CLOSE) { QList models = event->GetSaveables(); QHash modelsDecrementing; Saveable::Set modelsClosing; for (int i = 0; i < models.size(); i++) { this->IncrementRefCount(modelsDecrementing, models[i]); } this->FillModelsClosing(modelsClosing, modelsDecrementing); bool canceled = this->PromptForSavingIfNecessary( PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), modelsClosing, modelsDecrementing, !event->IsForce()); if (canceled) { event->SetVeto(true); } } else if (eventType == SaveablesLifecycleEvent::POST_CLOSE) { this->RemoveModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::DIRTY_CHANGED) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer lifeCycleEvent( new SaveablesLifecycleEvent(source, event->GetEventType(), event->GetSaveables(), false)); this->FireModelLifecycleEvent(lifeCycleEvent); } } void SaveablesList::AddModelLifecycleListener(ISaveablesLifecycleListener* listener) { events.AddListener(listener); } void SaveablesList::RemoveModelLifecycleListener(ISaveablesLifecycleListener* listener) { events.RemoveListener(listener); } SaveablesList::PostCloseInfo::Pointer SaveablesList::PreCloseParts( const QList& partsToClose, bool save, IWorkbenchWindow::Pointer window) { // reference count (how many occurrences of a model will go away?) PostCloseInfo::Pointer postCloseInfo(new PostCloseInfo()); for (QList::const_iterator it = partsToClose.begin(); it != partsToClose.end(); ++it) { WorkbenchPart::Pointer part = it->Cast(); postCloseInfo->partsClosing.push_back(part); if (part.Cast () != 0) { ISaveablePart::Pointer saveablePart = part.Cast(); if (save && !saveablePart->IsSaveOnCloseNeeded()) { // pretend for now that this part is not closing continue; } } // if (save && part.Cast () != 0) // { // ISaveablePart2 saveablePart2 = (ISaveablePart2) part; // // TODO show saveablePart2 before prompting, see // // EditorManager.saveAll // int response = SaveableHelper.savePart(saveablePart2, window, true); // if (response == ISaveablePart2.CANCEL) // { // // user canceled // return 0; // } // else if (response != ISaveablePart2.DEFAULT) // { // // only include this part in the following logic if it returned // // DEFAULT // continue; // } // } QList modelsFromSource = this->GetSaveables(part); for (int i = 0; i < modelsFromSource.size(); i++) { this->IncrementRefCount(postCloseInfo->modelsDecrementing, modelsFromSource[i]); } } this->FillModelsClosing(postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing); if (save) { bool canceled = this->PromptForSavingIfNecessary(window, postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing, true); if (canceled) { return PostCloseInfo::Pointer(0); } } return postCloseInfo; } bool SaveablesList::PromptForSaving( const QList& /*modelsToSave*/, /*final IShellProvider shellProvider, IRunnableContext runnableContext,*/ bool /*canCancel*/, bool /*stillOpenElsewhere*/) { // // Save parts, exit the method if cancel is pressed. // if (modelsToSave.size() > 0) { // boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave); // if (canceled) { // return true; // } // // IPreferenceStore apiPreferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean dontPrompt = stillOpenElsewhere && !apiPreferenceStore.getBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN); // // if (dontPrompt) { // modelsToSave.clear(); // return false; // } else if (modelsToSave.size() == 1) { // Saveable model = (Saveable) modelsToSave.get(0); // // Show a dialog. // QList buttons; // if(canCancel) { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // buttons.push_back(IDialogConstants.CANCEL_LABEL); // } else { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // } // // // don't save if we don't prompt // int choice = ISaveablePart2.NO; // // MessageDialog dialog; // if (stillOpenElsewhere) { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesOptionallyQuestion, // model.getName()); // MessageDialogWithToggle dialogWithToggle = new MessageDialogWithToggle(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0, WorkbenchMessages.EditorManager_closeWithoutPromptingOption, false) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // dialog = dialogWithToggle; // } else { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesQuestion, // model.getName()); // dialog = new MessageDialog(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // } // // choice = SaveableHelper.testGetAutomatedResponse(); // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // choice = dialog.open(); // // if(stillOpenElsewhere) { // // map value of choice back to ISaveablePart2 values // switch (choice) { // case IDialogConstants.YES_ID: // choice = ISaveablePart2.YES; // break; // case IDialogConstants.NO_ID: // choice = ISaveablePart2.NO; // break; // case IDialogConstants.CANCEL_ID: // choice = ISaveablePart2.CANCEL; // break; // default: // break; // } // MessageDialogWithToggle dialogWithToggle = (MessageDialogWithToggle) dialog; // if (choice != ISaveablePart2.CANCEL && dialogWithToggle.getToggleState()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // } // } // // // Branch on the user choice. // // The choice id is based on the order of button labels // // above. // switch (choice) { // case ISaveablePart2.YES: // yes // break; // case ISaveablePart2.NO: // no // modelsToSave.clear(); // break; // default: // case ISaveablePart2.CANCEL: // cancel // return true; // } // } else { // MyListSelectionDialog dlg = new MyListSelectionDialog( // shellProvider.getShell(), // modelsToSave, // new ArrayContentProvider(), // new WorkbenchPartLabelProvider(), // stillOpenElsewhere ? WorkbenchMessages.EditorManager_saveResourcesOptionallyMessage // : WorkbenchMessages.EditorManager_saveResourcesMessage, // canCancel, stillOpenElsewhere); // dlg.setInitialSelections(modelsToSave.toArray()); // dlg.setTitle(EditorManager.SAVE_RESOURCES_TITLE); // // // this "if" statement aids in testing. // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // int result = dlg.open(); // // Just return 0 to prevent the operation continuing // if (result == IDialogConstants.CANCEL_ID) // return true; // // if (dlg.getDontPromptSelection()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // // modelsToSave = Arrays.asList(dlg.getResult()); // } // } // } // // Create save block. // return saveModels(modelsToSave, shellProvider, runnableContext); return true; } bool SaveablesList::SaveModels(const QList& /*finalModels*/ /*final IShellProvider shellProvider, IRunnableContext runnableContext*/) { // IRunnableWithProgress progressOp = new IRunnableWithProgress() { // public void run(IProgressMonitor monitor) { // IProgressMonitor monitorWrap = new EventLoopProgressMonitor( // monitor); // monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$ // for (Iterator i = finalModels.iterator(); i.hasNext();) { // Saveable model = (Saveable) i.next(); // // handle case where this model got saved as a result of // // saving another // if (!model.isDirty()) { // monitor.worked(1); // continue; // } // SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, true); // if (monitorWrap.isCanceled()) // break; // } // monitorWrap.done(); // } // }; // // // Do the save. // return !SaveableHelper.runProgressMonitorOperation( // WorkbenchMessages.Save_All, progressOp, runnableContext, // shellProvider); return true; } void SaveablesList::PostClose(PostCloseInfo::Pointer postCloseInfo) { QList removed; for (QList::const_iterator it = postCloseInfo->partsClosing.begin(); it != postCloseInfo->partsClosing.end(); ++it) { IWorkbenchPart::Pointer part = *it; QHash::iterator it2 = modelMap.find(part.GetPointer()); if (it2 != modelMap.end()) { // make a copy to avoid a ConcurrentModificationException - we // will remove from the original set as we iterate Saveable::Set saveables(it2.value()); for (Saveable::Set::const_iterator it3 = saveables.begin(); it3 != saveables.end(); ++it3) { if (RemoveModel(part, *it3)) { removed.push_back(*it3); } } } } if (!removed.empty()) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_CLOSE, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::PostOpen(IWorkbenchPart::Pointer part) { this->AddModels(part, this->GetSaveables(part)); } void SaveablesList::DirtyChanged(IWorkbenchPart::Pointer part) { QList saveables = this->GetSaveables(part); if (saveables.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::DIRTY_CHANGED, saveables, false)); this->FireModelLifecycleEvent(event); } } QList SaveablesList::TestGetSourcesForModel( Saveable::Pointer /*model*/) { QList result; // for (Iterator it = modelMap.entrySet().iterator(); it.hasNext();) { // Map.Entry entry = (Map.Entry) it.next(); // Set values = (Set) entry.getValue(); // if (values.contains(model)) { // result.add(entry.getKey()); // } // } return result; } QList SaveablesList::GetNonPartSources() { return nonPartSources.toList(); } QList SaveablesList::GetPartsForSaveable( Saveable::Pointer model) { QList result; for (QHash::iterator it = modelMap.begin(); it != modelMap.end(); ++it) { Saveable::Set& values = it.value(); IWorkbenchPart::Pointer part(dynamic_cast(it.key())); if (values.find(model) != values.end() && part) { result.push_back(part); } } return result; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp index b8a370c728..c61f397d45 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp @@ -1,268 +1,267 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryShowViewMenu.h" #include #include #include #include #include #include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryViewDescriptor.h" #include "intro/berryIntroConstants.h" #include #include #include namespace berry { struct ActionComparator { bool operator()(const CommandContributionItemParameter::Pointer& p1, const CommandContributionItemParameter::Pointer& p2) const { return p1->label < p2->label; } }; ShowViewMenu::ShowViewMenu(IWorkbenchWindow *window, const QString& id) : ContributionItem(id), dirty(true), window(window) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( window, QString::null, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // window.getWorkbench().getHelpSystem().setHelp(showDlgAction, // IWorkbenchHelpContextIds.SHOW_VIEW_OTHER_ACTION); // // indicate that a show views submenu has been created // if (window instanceof WorkbenchWindow) { // ((WorkbenchWindow) window) // .addSubmenu(WorkbenchWindow.SHOW_VIEW_SUBMENU); // } } bool ShowViewMenu::IsDirty() const { return dirty; } /** * Overridden to always return true and force dynamic menu building. */ bool ShowViewMenu::IsDynamic() const { return true; } QAction* ShowViewMenu::Fill(QMenu* menu, QAction* before) { // if (MenuManager::Pointer mm = GetParent().Cast()) // { // mm->AddMenuListener(menuListener); // } if (!dirty) { return 0; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); if (items.size() == 0) { QAction* action = new QAction("No Views registered", menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { before = item->Fill(menu, before); } } dirty = false; return before; } void ShowViewMenu::FillMenu(IMenuManager* innerMgr) { // Remove all. innerMgr->RemoveAll(); // If no page disable all. IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } // If no active perspective disable all if (page->GetPerspective().IsNull()) { return; } typedef QPair ViewIdPair; // Get visible actions. QSet viewIds = GetShortcuts(page.GetPointer()); // add all open views viewIds = AddOpenedViews(page.GetPointer(), viewIds); QList actions; foreach (ViewIdPair id, viewIds) { if (id.first == IntroConstants::INTRO_VIEW_ID) { continue; } CommandContributionItemParameter::Pointer item = GetItem(id.first, id.second); if (item) { actions.append(item); } } qSort(actions.begin(), actions.end(), ActionComparator()); foreach (CommandContributionItemParameter::Pointer ccip, actions) { // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); innerMgr->Add(item); } // We only want to add the separator if there are show view shortcuts, // otherwise, there will be a separator and then the 'Other...' entry // and that looks weird as the separator is separating nothing if (!innerMgr->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); innerMgr->Add(separator); } // Add Other... innerMgr->Add(showDlgItem); } QSet > ShowViewMenu::GetShortcuts(IWorkbenchPage* page) const { QSet > list; QList shortcuts(page->GetShowViewShortcuts()); for (int i = 0; i < shortcuts.size(); ++i) { list.insert(qMakePair(shortcuts[i], QString())); } return list; } CommandContributionItemParameter::Pointer ShowViewMenu::GetItem(const QString& viewId, const QString& secondaryId) const { IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(viewId); if (desc.IsNull()) { return CommandContributionItemParameter::Pointer(0); } QString label = desc->GetLabel(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: PluginCCIP(const IViewDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { ViewDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const { return localId; } QString GetPluginId() const { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, viewId, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); parms->label = label; - QIcon icon(*(reinterpret_cast(desc->GetImageDescriptor()->CreateImage()))); - parms->icon = icon; + parms->icon = desc->GetImageDescriptor(); Object::Pointer strViewId(new ObjectString(viewId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID, strViewId); // if (makeFast) // { // parms.parameters.put( // IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW, // "true"); //$NON-NLS-1$ // } if (!secondaryId.isEmpty()) { Object::Pointer strSecondaryId(new ObjectString(secondaryId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID, strSecondaryId); } return parms; } QSet > ShowViewMenu::AddOpenedViews(IWorkbenchPage* page, QSet >& actions) const { QSet > views = GetParts(page); return views.unite(actions); } QSet > ShowViewMenu::GetParts(IWorkbenchPage* page) const { QSet > parts; QList refs = page->GetViewReferences(); for (int i = 0; i < refs.size(); ++i) { parts.insert(qMakePair(refs[i]->GetId(), refs[i]->GetSecondaryId())); } return parts; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp index a23f9b1783..2f999bd082 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp @@ -1,218 +1,210 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewDescriptor.h" #include "berryIConfigurationElement.h" #include "berryCoreException.h" #include "berryIExtension.h" #include "berryIContributor.h" #include "berryStatus.h" #include "berryRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" -#include "berryImageDescriptor.h" #include "berryAbstractUICTKPlugin.h" -#include "berryImageDescriptor.h" #include "handlers/berryIHandlerActivation.h" namespace berry { ViewDescriptor::ViewDescriptor(const IConfigurationElement::Pointer& e) : configElement(e) { this->LoadFromExtension(); } IViewPart::Pointer ViewDescriptor::CreateView() { IViewPart::Pointer part(configElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return part; } QStringList ViewDescriptor::GetCategoryPath() const { return categoryPath; } IConfigurationElement::Pointer ViewDescriptor::GetConfigurationElement() const { return configElement; } QString ViewDescriptor::GetDescription() const { return RegistryReader::GetDescription(configElement); } QString ViewDescriptor::GetId() const { return id; } bool ViewDescriptor::operator==(const Object* o) const { if (const IViewDescriptor* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } -ImageDescriptor::Pointer ViewDescriptor::GetImageDescriptor() const +QIcon ViewDescriptor::GetImageDescriptor() const { - if (imageDescriptor) + if (!imageDescriptor.isNull()) { return imageDescriptor; } QString iconName = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); // If the icon attribute was omitted, use the default one if (iconName.isEmpty()) { //TODO default image descriptor //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); - return ImageDescriptor::GetMissingImageDescriptor(); + return AbstractUICTKPlugin::GetMissingIcon(); } IExtension::Pointer extension(configElement->GetDeclaringExtension()); const QString extendingPluginId(extension->GetContributor()->GetName()); imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); - if (!imageDescriptor) - { - // Try legacy BlueBerry method - imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( - extendingPluginId, iconName); - } // If the icon attribute was invalid, use the error icon - if (!imageDescriptor) + if (imageDescriptor.isNull()) { - imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); + imageDescriptor = AbstractUICTKPlugin::GetMissingIcon(); } return imageDescriptor; } QString ViewDescriptor::GetLabel() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString ViewDescriptor::GetAccelerator() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ACCELERATOR); } bool ViewDescriptor::GetAllowMultiple() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE).compare("true", Qt::CaseInsensitive) == 0; } bool ViewDescriptor::IsRestorable() const { QString str = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_RESTORABLE); return str.isNull() ? true : str.compare("true", Qt::CaseInsensitive) == 0; } Object* ViewDescriptor::GetAdapter(const QString& adapter) { if (adapter == qobject_interface_iid()) { return GetConfigurationElement().GetPointer(); } return NULL; } void ViewDescriptor::ActivateHandler() { //TODO ViewDescriptor handler activation // if (!handlerActivation) // { // IHandler::Pointer handler(new ShowViewHandler(this->GetId())); // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerActivation = handlerService // ->ActivateHandler(this->GetId(), handler); // } } void ViewDescriptor::DeactivateHandler() { //TODO ViewDescriptor handler deactivation // if (handlerActivation) // { // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerService->DeactivateHandler(handlerActivation); // handlerActivation = 0; // } } QStringList ViewDescriptor::GetKeywordReferences() const { QStringList result; auto keywordRefs = configElement->GetChildren("keywordReference"); for (auto keywordRefsIt = keywordRefs.begin(); keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString ViewDescriptor::GetPluginId() const { return configElement->GetContributor()->GetName(); } QString ViewDescriptor::GetLocalId() const { return this->GetId(); } void ViewDescriptor::LoadFromExtension() { id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); // Sanity check. QString name = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); if (name.isEmpty() || RegistryReader::GetClassValue(configElement, WorkbenchRegistryConstants::ATT_CLASS).isEmpty()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, configElement->GetContributor()->GetName(), 0, QString("Invalid extension (missing label or class name): ") + id)); throw CoreException(status); } QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); if (!category.isEmpty()) { // Parse the path tokens and store them foreach (QString pathElement, category.split('/', QString::SkipEmptyParts)) { if (!pathElement.trimmed().isEmpty()) { categoryPath.push_back(pathElement.trimmed()); } } } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h index 80c18f0f76..650dfc7188 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h @@ -1,163 +1,164 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYVIEWDESCRIPTOR_H_ #define BERRYVIEWDESCRIPTOR_H_ #include "berryIViewPart.h" #include "berryIViewDescriptor.h" #include "berryIPluginContribution.h" #include +#include namespace berry { struct IConfigurationElement; struct IHandlerActivation; /** * \ingroup org_blueberry_ui_internal * */ class ViewDescriptor : public IViewDescriptor, public IPluginContribution { private: QString id; - mutable SmartPointer imageDescriptor; + mutable QIcon imageDescriptor; IConfigurationElement::Pointer configElement; QStringList categoryPath; /** * The activation token returned when activating the show view handler with * the workbench. */ SmartPointer handlerActivation; public: berryObjectMacro(ViewDescriptor); /** * Create a new ViewDescriptor for an extension. * * @param e the configuration element * @throws CoreException thrown if there are errors in the configuration */ ViewDescriptor(const SmartPointer& e); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#createView() */ IViewPart::Pointer CreateView(); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getCategoryPath() */ QStringList GetCategoryPath() const; /** * Return the configuration element for this descriptor. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getDescription() */ QString GetDescription() const; QStringList GetKeywordReferences() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getId() */ QString GetId() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getImageDescriptor() */ - SmartPointer GetImageDescriptor() const; + QIcon GetImageDescriptor() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getLabel() */ QString GetLabel() const; /** * Return the accelerator attribute. * * @return the accelerator attribute */ QString GetAccelerator() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getAllowMultiple() */ bool GetAllowMultiple() const; /* (non-Javadoc) * @see org.eclipse.ui.views.IViewDescriptor#getRestorable() */ bool IsRestorable() const; bool operator==(const Object*) const; /** * Activates a show view handler for this descriptor. This handler can later * be deactivated by calling {@link ViewDescriptor#deactivateHandler()}. * This method will only activate the handler if it is not currently active. * */ void ActivateHandler(); /** * Deactivates the show view handler for this descriptor. This handler was * previously activated by calling {@link ViewDescriptor#activateHandler()}. * This method will only deactivative the handler if it is currently active. * */ void DeactivateHandler(); /* * @see IPluginContribution#GetPluginId() */ QString GetPluginId() const; /* * @see IPluginContribution#GetLocalId() */ QString GetLocalId() const; protected: /* (non-Javadoc) * @see IAdaptable#GetAdapterImpl(const std::type_info&) */ Object* GetAdapter(const QString& adapter); private: /** * load a view descriptor from the registry. */ void LoadFromExtension(); }; } #endif /*BERRYVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp index 9efae57c0f..e425e6b43d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp @@ -1,324 +1,323 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewFactory.h" #include "berryUIException.h" #include "berryIViewRegistry.h" -#include "berryImageDescriptor.h" #include "berryViewReference.h" #include "berryViewDescriptor.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" #include "util/berrySafeRunnable.h" #include namespace berry { const QString ViewFactory::ID_SEP = ":"; //$NON-NLS-1$ QString ViewFactory::GetKey(const QString& id, const QString& secondaryId) { return secondaryId.isEmpty() ? id : id + ID_SEP + secondaryId; } QString ViewFactory::GetKey(IViewReference::Pointer viewRef) { return GetKey(viewRef->GetId(), viewRef->GetSecondaryId()); } QString ViewFactory::ExtractPrimaryId(const QString& compoundId) { int i = compoundId.lastIndexOf(ID_SEP); if (i == -1) { return compoundId; } return compoundId.left(i); } QString ViewFactory::ExtractSecondaryId(const QString& compoundId) { int i = compoundId.lastIndexOf(ID_SEP); if (i == -1) { return QString(); } return compoundId.mid(i + 1); } bool ViewFactory::HasWildcard(const QString& viewId) { return viewId.indexOf('*') != -1; } ViewFactory::ViewFactory(WorkbenchPage* p, IViewRegistry* reg) : page(p), viewReg(reg) { //page.getExtensionTracker().registerHandler(this, null); } IViewReference::Pointer ViewFactory::CreateView(const QString& id, const QString& secondaryId) { IViewDescriptor::Pointer desc = viewReg->Find(id); // ensure that the view id is valid if (desc.IsNull()) { throw PartInitException(QString("Could not create view: ") + id); } // ensure that multiple instances are allowed if a secondary id is given if (secondaryId != "") { if (!desc->GetAllowMultiple()) { throw PartInitException(QString("View does not allow multiple instances:") + id); } } QString key = this->GetKey(id, secondaryId); IViewReference::Pointer ref = counter.Get(key); if (ref.IsNull()) { IMemento::Pointer memento = mementoTable[key]; ref = new ViewReference(this, id, secondaryId, memento); mementoTable.remove(key); counter.Put(key, ref); this->GetWorkbenchPage()->PartAdded(ref.Cast ()); } else { counter.AddRef(key); } return ref; } QList ViewFactory::GetViewReferences() { QList values(counter.Values()); return values; } IViewReference::Pointer ViewFactory::GetView(const QString& id) { return this->GetView(id, ""); } IViewReference::Pointer ViewFactory::GetView(const QString& id, const QString& secondaryId) { QString key = this->GetKey(id, secondaryId); return counter.Get(key); } const IViewRegistry* ViewFactory::GetViewRegistry() const { return viewReg; } QList ViewFactory::GetViews() { QList values(counter.Values()); return values; } WorkbenchPage* ViewFactory::GetWorkbenchPage() const { return page; } int ViewFactory::GetReferenceCount(IViewReference::Pointer viewRef) { QString key = this->GetKey(viewRef); IViewReference::Pointer ref = counter.Get(key); return ref.IsNull() ? 0 : counter.GetRef(key); } void ViewFactory::ReleaseView(IViewReference::Pointer viewRef) { QString key = this->GetKey(viewRef); IViewReference::Pointer ref = counter.Get(key); if (ref.IsNull()) { return; } int count = counter.RemoveRef(key); if (count <= 0) { this->GetWorkbenchPage()->PartRemoved(ref.Cast ()); } } bool ViewFactory::RestoreState(IMemento::Pointer memento) { QList mem(memento->GetChildren( WorkbenchConstants::TAG_VIEW)); for (int i = 0; i < mem.size(); i++) { //for dynamic UI - add the next line to replace subsequent code that is commented out RestoreViewState(mem[i]); } // return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ return true; } bool ViewFactory::SaveState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.ViewFactory_problemsSavingViews, null); bool result = true; QList refs(GetViews()); for (int i = 0; i < refs.size(); i++) { IViewDescriptor::Pointer desc = viewReg->Find(refs[i]->GetId()); if (desc->IsRestorable()) { //for dynamic UI - add the following line to replace subsequent code which is commented out SaveViewState(memento, refs[i], result); } } return result; } struct SaveViewRunnable: public SafeRunnable { SaveViewRunnable(IViewPart::Pointer view, IMemento::Pointer viewMemento, bool& result) : view(view), viewMemento(viewMemento), result(result) { } void Run() { const QHash& properties = view->GetPartProperties(); if (!properties.empty()) { IMemento::Pointer propBag = viewMemento ->CreateChild( WorkbenchConstants::TAG_PROPERTIES); for (QHash::const_iterator i = properties.begin(); i != properties.end(); ++i) { IMemento::Pointer p = propBag->CreateChild( WorkbenchConstants::TAG_PROPERTY, i.key()); p->PutTextData(i.value()); } } view->SaveState(viewMemento ->CreateChild( WorkbenchConstants::TAG_VIEW_STATE)); } void HandleException(const std::exception& /*e*/) { // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // NLS.bind(WorkbenchMessages.ViewFactory_couldNotSave, viewRef.getTitle() ), // e)); result = false; } private: IViewPart::Pointer view; IMemento::Pointer viewMemento; bool& result; }; // for dynamic UI IMemento::Pointer ViewFactory::SaveViewState(IMemento::Pointer memento, IViewReference::Pointer ref, bool& res) { //final MultiStatus result = res; bool& result = res; IMemento::Pointer viewMemento = memento->CreateChild( WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref)); if (ViewReference::Pointer viewRef = ref.Cast()) { viewMemento->PutString(WorkbenchConstants::TAG_PART_NAME, viewRef->GetPartName()); } const IViewReference::Pointer viewRef = ref; const IViewPart::Pointer view = ref->GetPart(false).Cast (); if (view) { ISafeRunnable::Pointer runnable(new SaveViewRunnable(view, viewMemento, result)); SafeRunner::Run(runnable); } else { IMemento::Pointer mem; IMemento::Pointer props; // if we've created the reference once, any previous workbench // state memento is there. After once, there is no previous // session state, so it should be null. if (ref.Cast ()) { mem = ref.Cast ()->GetMemento(); if (mem) { props = mem->GetChild(WorkbenchConstants::TAG_PROPERTIES); mem = mem->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } } if (props) { viewMemento->CreateChild(WorkbenchConstants::TAG_PROPERTIES) ->PutMemento( props); } if (mem) { IMemento::Pointer child = viewMemento ->CreateChild( WorkbenchConstants::TAG_VIEW_STATE); child->PutMemento(mem); } } return viewMemento; } // for dynamic UI void ViewFactory::RestoreViewState(IMemento::Pointer memento) { QString compoundId; memento->GetString(WorkbenchConstants::TAG_ID, compoundId); mementoTable.insert(compoundId, memento); } IMemento::Pointer ViewFactory::GetViewState(const QString& key) { IMemento::Pointer memento = mementoTable[key]; if (!memento) return IMemento::Pointer(0); return memento->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewLayout.cpp index 4453b0b003..71a7feb03f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewLayout.cpp @@ -1,61 +1,59 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewLayout.h" -#include "berryImageDescriptor.h" - namespace berry { ViewLayout::ViewLayout(PageLayout::Pointer pageLayout, ViewLayoutRec::Pointer r) : rec(r) { poco_assert(pageLayout != 0); poco_assert(rec != 0); } bool ViewLayout::GetShowTitle() { return rec->showTitle; } bool ViewLayout::IsCloseable() { return rec->isCloseable; } bool ViewLayout::IsMoveable() { return rec->isMoveable; } bool ViewLayout::IsStandalone() { return rec->isStandalone; } void ViewLayout::SetCloseable(bool closeable) { rec->isCloseable = closeable; } void ViewLayout::SetMoveable(bool moveable) { rec->isMoveable = moveable; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp index cce6495a9e..058aef6009 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp @@ -1,445 +1,444 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewReference.h" #include #include "berryUIException.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryPlatformUI.h" -#include "berryImageDescriptor.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" #include "berryViewDescriptor.h" #include "berryViewFactory.h" #include "berryViewRegistry.h" #include "berryViewSite.h" #include "berryPartTester.h" #include "berryWorkbenchPlugin.h" #include "berryErrorViewPart.h" namespace berry { ViewReference::ViewReference(ViewFactory* fac, const QString& id, const QString& secId, IMemento::Pointer m) : factory(fac), secondaryId(secId), memento(m) { ViewDescriptor::Pointer desc = this->factory->GetViewRegistry()->Find(id).Cast (); - ImageDescriptor::Pointer iDesc; + QIcon iDesc; QString title; if (!desc.IsNull()) { iDesc = desc->GetImageDescriptor(); title = desc->GetLabel(); } QString name; if (!memento.IsNull()) { // name = memento.getString(IWorkbenchConstants.TAG_PART_NAME); // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } } if (name.isEmpty()) { name = title; } this->Init(id, "", iDesc, name, ""); //$NON-NLS-1$//$NON-NLS-2$ } void ViewReference::DoDisposePart() { IViewPart::Pointer view = part.Cast (); //WorkbenchPartReference::DoDisposePart(); if (!view.IsNull()) { // Free action bars, pane, etc. //PartSite site = (PartSite) view.getSite(); //ViewActionBars actionBars = (ViewActionBars) site.getActionBars(); // // 3.3 start // //IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getMenuManager()); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getToolBarManager()); // 3.3 end //actionBars.dispose(); // and now dispose the delegates since the // PluginActionContributionItem // can no longer do that // if (actionBuilder != null) { // actionBuilder.dispose(); // actionBuilder = null; // } // Free the site. //site.dispose(); } } IWorkbenchPage::Pointer ViewReference::GetPage() const { return IWorkbenchPage::Pointer(this->factory->GetWorkbenchPage()); } QString ViewReference::GetRegisteredName() { if (!part.IsNull() && !part->GetSite().IsNull()) { return part->GetSite()->GetRegisteredName(); } const IViewRegistry* reg = this->factory->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(this->GetId()); if (!desc.IsNull()) { return desc->GetLabel(); } return this->GetPartName(); } QString ViewReference::GetSecondaryId() { return secondaryId; } IViewPart::Pointer ViewReference::GetView(bool restore) { return this->GetPart(restore).Cast (); } IWorkbenchPart::Pointer ViewReference::CreatePart() { // Check the status of this part IWorkbenchPart::Pointer result; PartInitException* exception = 0; // Try to restore the view -- this does the real work of restoring the // view // try { result = this->CreatePartHelper(); } catch (const PartInitException& e) { exception = e.clone(); } // If unable to create the part, create an error part instead // and pass the error to the status handling facility if (exception != 0) { // IStatus partStatus = exception.getStatus(); // IStatus displayStatus = StatusUtil.newStatus(partStatus, // NLS.bind(WorkbenchMessages.ViewFactory_initException, partStatus.getMessage())); // IStatus logStatus = StatusUtil // .newStatus( // partStatus, // NLS // .bind( // "Unable to create view ID {0}: {1}", getId(), partStatus.getMessage())); //$NON-NLS-1$ // Pass the error to the status handling facility // StatusManager.getManager().handle(logStatus); QString errorTitle = "Unable to create view ID " + this->GetId(); WorkbenchPlugin::Log(errorTitle + ": " + exception->what()); IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find( this->GetId()); QString label = this->GetId(); if (!desc.IsNull()) { label = desc->GetLabel(); } QString errorMsg(exception->what()); delete exception; errorMsg += "
  • Check your shared library for unresolved symbols
  • " "
  • Check your class attribute in your plugin.xml file
  • " "
  • Check your manifest.cpp file
" "
For a comprehensive check-list, see http://www.mitk.org/wiki/How_to_fix_your_plug-in_DLL"; ErrorViewPart::Pointer part(new ErrorViewPart(errorTitle, errorMsg)); //PartPane pane = getPane(); IViewReference::Pointer viewRef(this); ViewSite::Pointer site(new ViewSite(viewRef, part, factory->GetWorkbenchPage(), GetId(), PlatformUI::PLUGIN_ID(), label)); //site.setActionBars(new ViewActionBars(factory.page.getActionBars(), // site, (ViewPane) pane)); try { part->Init(site); } catch (const PartInitException& e) { BERRY_ERROR << e.what(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } part->SetPartName(label); void* parent = pane->GetControl(); try { part->CreatePartControl(parent); } catch (const std::exception& e) { BERRY_ERROR << "Error creating view: " << e.what() << std::endl; // StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } return result; } PartPane::Pointer ViewReference::CreatePane() { IWorkbenchPartReference::Pointer partRef(this); PartPane::Pointer pane(new PartPane(partRef, this->factory->GetWorkbenchPage())); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateViewPane(this, this->factory->GetWorkbenchPage()); } IWorkbenchPart::Pointer ViewReference::CreatePartHelper() { IWorkbenchPart::Pointer result; IMemento::Pointer stateMem; if (!memento.IsNull()) { stateMem = memento->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find(GetId()); if (desc.IsNull()) { throw PartInitException(QString("Could not create view: ") + this->GetId()); } // Create the part pane PartPane::Pointer pane = this->GetPane(); // Create the pane's top-level control pane->CreateControl(factory->GetWorkbenchPage()->GetClientComposite()); QString label = desc->GetLabel(); // debugging only // Things that will need to be disposed if an exception occurs (they are // listed here // in the order they should be disposed) //Composite content = null; IViewPart::Pointer initializedView; ViewSite::Pointer site; //ViewActionBars actionBars = null; // End of things that need to be explicitly disposed from the try block try { IViewPart::Pointer view; view = desc->CreateView(); if (view.IsNull()) return result; this->CreatePartProperties(view); // Create site IViewReference::Pointer viewRef(this); site = new ViewSite(viewRef, view, factory->GetWorkbenchPage(), desc); //actionBars = new ViewActionBars(factory.page.getActionBars(), site, // (ViewPane) pane); //site.setActionBars(actionBars); view->Init(site, stateMem); // Once we've called init, we MUST dispose the view. Remember // the fact that // we've initialized the view in case an exception is thrown. initializedView = view; if (view->GetSite() != site) { throw PartInitException("View initialization failed. Site is incorrect."); } // Create the top-level composite { void* parent = pane->GetControl(); view->CreatePartControl(parent); } // Install the part's tools and menu { // // 3.3 start // // IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); // menuService.populateContributionManager( // (ContributionManager) site.getActionBars() // .getMenuManager(), "menu:" //$NON-NLS-1$ // + site.getId()); // menuService // .populateContributionManager((ContributionManager) site // .getActionBars().getToolBarManager(), // "toolbar:" + site.getId()); //$NON-NLS-1$ // 3.3 end // actionBuilder = new ViewActionBuilder(); // actionBuilder.readActionExtensions(view); // ActionDescriptor[] actionDescriptors = actionBuilder // .getExtendedActions(); // IKeyBindingService keyBindingService = view.getSite() // .getKeyBindingService(); // // if (actionDescriptors != null) { // for (int i = 0; i < actionDescriptors.length; i++) { // ActionDescriptor actionDescriptor = actionDescriptors[i]; // // if (actionDescriptor != null) { // IAction action = actionDescriptors[i].getAction(); // // if (action != null // && action.getActionDefinitionId() != null) { // keyBindingService.registerAction(action); // } // } // } // } // // site.getActionBars().updateActionBars(); } // The part should now be fully created. Exercise its public // interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave // badly, it's much better // that it does so now while we can still cancel creation of the // part. PartTester::TestView(view); result = view.Cast (); // IConfigurationElement::Pointer element = desc->GetConfigurationElement(); // if (!element.IsNull()) { // factory.page.getExtensionTracker().registerObject( // element.getDeclaringExtension(), view, // IExtensionTracker.REF_WEAK); // } } catch (const ctkException& e) { // if ((e instanceof Error) && !(e instanceof LinkageError)) { // throw (Error) e; // } // An exception occurred. First deallocate anything we've allocated // in the try block (see the top // of the try block for a list of objects that need to be explicitly // disposed) // if (content != null) { // try { // content.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (initializedView != null) { // try { // initializedView.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (site != null) { // try { // site.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (actionBars != null) { // try { // actionBars.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } throw PartInitException(e.what(), e); } catch (const std::exception& e) { throw PartInitException(e.what()); } return result; } IMemento::Pointer ViewReference::GetMemento() { return memento; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp index 866b8a9071..2abf399801 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp @@ -1,276 +1,275 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewRegistry.h" #include "berryPlatformUI.h" -#include "berryImageDescriptor.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPlatform.h" namespace berry { ViewRegistry::ViewCategoryProxy::ViewCategoryProxy( IViewDescriptorCategoryPtr rawCategory) : rawCategory(rawCategory) { } QList ViewRegistry::ViewCategoryProxy::GetViews() const { return rawCategory->GetElements(); } QString ViewRegistry::ViewCategoryProxy::GetId() const { return rawCategory->GetId(); } QStringList ViewRegistry::ViewCategoryProxy::GetPath() const { QList path; QString rawParentPath = rawCategory->GetRawParentPath(); // nested categories are not supported yet // assume an empty raw parent path path.push_back(rawParentPath); return path; } QString ViewRegistry::ViewCategoryProxy::GetLabel() const { return rawCategory->GetLabel(); } bool ViewRegistry::ViewCategoryProxy::operator==(const Object* o) const { if (const IViewCategory* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } uint ViewRegistry::ViewCategoryProxy::HashCode() const { return qHash(GetId()); } QString ViewRegistry::EXTENSIONPOINT_UNIQUE_ID = "org.blueberry.ui.views"; // PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_VIEWS; Category::Pointer ViewRegistry::InternalFindCategory(const QString& id) { for (QList::iterator itr = categories.begin(); itr != categories.end(); ++itr) { if (id == (*itr)->GetRootPath()) { return *itr; } } return IViewDescriptorCategoryPtr(0); } IExtensionPoint::Pointer ViewRegistry::GetExtensionPointFilter() { return Platform::GetExtensionRegistry()->GetExtensionPoint(EXTENSIONPOINT_UNIQUE_ID); } const QString ViewRegistry::TAG_DESCRIPTION = "description"; ViewRegistry::ViewRegistry() : dirtyViewCategoryMappings(true) { miscCategory = new IViewDescriptorCategory(); this->Add(miscCategory); //PlatformUI.getWorkbench().getExtensionTracker().registerHandler(this, // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); reader.ReadViews(this); } void ViewRegistry::Add(IViewDescriptorCategoryPtr desc) { /* fix for 1877 */ if (this->InternalFindCategory(desc->GetId()).IsNull()) { dirtyViewCategoryMappings = true; // Mark categories list as dirty categories.push_back(desc); // IConfigurationElement::Pointer element( // dynamic_cast( // desc->GetAdapter(typeid(IConfigurationElement)) // )); // if (element.IsNull()) // { // return; // } // PlatformUI::GetWorkbench()->GetExtensionTracker() // .registerObject(element->GetDeclaringExtension(), desc, // IExtensionTracker::REF_WEAK); } } void ViewRegistry::Add(ViewDescriptor::Pointer desc) { for (QList::const_iterator itr = views.begin(); itr != views.end(); ++itr) { if (desc.GetPointer() == itr->GetPointer()) return; } views.push_back(desc); dirtyViewCategoryMappings = true; //desc.activateHandler(); } void ViewRegistry::Add(StickyViewDescriptor::Pointer desc) { if (std::find(sticky.begin(), sticky.end(), desc) == sticky.end()) { sticky.push_back(desc); // PlatformUI::GetWorkbench()->GetExtensionTracker() // .registerObject(desc.getConfigurationElement().getDeclaringExtension(), // desc, IExtensionTracker.REF_WEAK); } } IViewDescriptor::Pointer ViewRegistry::Find(const QString& id) const { for (QList::const_iterator itr = views.begin(); itr != views.end(); ++itr) { if (id == (*itr)->GetId()) { return *itr; } } return IViewDescriptor::Pointer(0); } IViewCategory::Pointer ViewRegistry::FindCategory(const QString& id) { this->MapViewsToCategories(); IViewDescriptorCategoryPtr category(this->InternalFindCategory(id)); if (category.IsNull()) { return IViewCategory::Pointer(0); } IViewCategory::Pointer cat(new ViewCategoryProxy(category)); return cat; } QList ViewRegistry::GetCategories() { this->MapViewsToCategories(); QList retArray; for (QList::iterator itr = categories.begin(); itr != categories.end(); ++itr) { retArray.push_back(IViewCategory::Pointer(new ViewCategoryProxy(*itr))); } return retArray; } QList ViewRegistry::GetStickyViews() const { return sticky; } Category::Pointer ViewRegistry::GetMiscCategory() const { return miscCategory; } QList ViewRegistry::GetViews() const { return views; } void ViewRegistry::MapViewsToCategories() { if (dirtyViewCategoryMappings) { dirtyViewCategoryMappings = false; // clear all category mappings for (QList::iterator i = categories.begin(); i != categories.end(); ++i) { (*i)->Clear(); // this is bad } miscCategory->Clear(); for (QList::iterator i = views.begin(); i != views.end(); ++i) { IViewDescriptor::Pointer desc(*i); IViewDescriptorCategoryPtr cat(0); const QList& catPath = desc->GetCategoryPath(); if (catPath.size() > 0) { cat = this->InternalFindCategory(catPath[0]); } if (cat.IsNotNull()) { if (!cat->HasElement(desc)) { cat->AddElement(desc); } } else { if (catPath.size() > 0) { // If we get here, this view specified a category which // does not exist. Add this view to the 'Other' category // but give out a message (to the log only) indicating // this has been done. QString fmt("Category %1 not found for view %2. This view added to ''%3'' category."); WorkbenchPlugin::Log(fmt.arg(catPath[0]).arg(desc->GetId()).arg(miscCategory->GetLabel())); } miscCategory->AddElement(desc); } } } } //void ViewRegistry::AddExtension(IExtensionTracker tracker, // IExtension addedExtension) //{ // IConfigurationElement[] addedElements = addedExtension.getConfigurationElements(); // for (int i = 0; i < addedElements.length; i++) // { // IConfigurationElement element = addedElements[i]; // if (element.getName().equals(IWorkbenchRegistryConstants.TAG_VIEW)) // { // reader.readView(element); // } // else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_CATEGORY)) // { // reader.readCategory(element); // } // else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_STICKYVIEW)) // { // reader.readSticky(element); // } // } //} } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp index 5ffd06db6f..86f10e2f9f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp @@ -1,114 +1,113 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewRegistryReader.h" #include "berryViewRegistry.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" -#include "berryImageDescriptor.h" #include "berryPlatformUI.h" namespace berry { QString ViewRegistryReader::GENERAL_VIEW_ID = "org.blueberry.ui"; ViewRegistryReader::ViewRegistryReader() : RegistryReader() { } void ViewRegistryReader::ReadViews(ViewRegistry* out) { // this does not seem to really ever be throwing an the exception viewRegistry = out; this->ReadRegistry(PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_VIEWS); } void ViewRegistryReader::ReadCategory(const IConfigurationElement::Pointer& element) { try { Category::Pointer cat(new Category(element)); viewRegistry->Add(cat); } catch (CoreException e) { // log an error since its not safe to show a dialog here WorkbenchPlugin::Log( "Unable to create view category.", e);//$NON-NLS-1$ } } bool ViewRegistryReader::ReadElement(const SmartPointer &element) { QString elementName = element->GetName(); if (elementName == WorkbenchRegistryConstants::TAG_VIEW) { this->ReadView(element); return true; } if (elementName == WorkbenchRegistryConstants::TAG_CATEGORY) { this->ReadCategory(element); this->ReadElementChildren(element); return true; } if (elementName == WorkbenchRegistryConstants::TAG_STICKYVIEW) { this->ReadSticky(element); return true; } return false; } void ViewRegistryReader::ReadSticky(const SmartPointer &element) { try { viewRegistry->Add(StickyViewDescriptor::Pointer(new StickyViewDescriptor(element))); } catch (CoreException& e) { //TODO IStatus // log an error since its not safe to open a dialog here // WorkbenchPlugin.log( // "Unable to create sticky view descriptor.", e.getStatus());//$NON-NLS-1$ WorkbenchPlugin::Log("Unable to create sticky view descriptor.", e); } } void ViewRegistryReader::ReadView(const SmartPointer &element) { try { ViewDescriptor::Pointer desc(new ViewDescriptor(element)); viewRegistry->Add(desc); } catch (CoreException e) { // log an error since its not safe to open a dialog here WorkbenchPlugin::Log( "Unable to create view descriptor.", e);//$NON-NLS-1$ } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp index 3e5f69623c..10b29d413b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp @@ -1,294 +1,292 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewSashContainer.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" -#include "berryImageDescriptor.h" - namespace berry { ViewSashContainer::ViewSashContainer(WorkbenchPage* page, void* parent) : PartSashContainer("root layout container", page, parent) { } ViewSashContainer::Pointer ViewSashContainer::GetRootContainer() { return ViewSashContainer::Pointer(this); } void* ViewSashContainer::GetControl() { return this->parent; } bool ViewSashContainer::RestoreState(IMemento::Pointer memento) { //TODO ViewSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, null); // bool result = true; // Read the info elements. QList children(memento->GetChildren(WorkbenchConstants::TAG_INFO)); // Create a part ID to part hashtable. QHash mapIDtoPart; // Loop through the info elements. for (int i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; QString partID; childMem->GetString(WorkbenchConstants::TAG_PART, partID); QString relativeID; childMem->GetString(WorkbenchConstants::TAG_RELATIVE, relativeID); int relationship = 0; int left = 0, right = 0; if (!relativeID.isEmpty()) { childMem->GetInteger(WorkbenchConstants::TAG_RELATIONSHIP, relationship); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_LEFT, left); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_RIGHT, right); } QString strFolder; childMem->GetString(WorkbenchConstants::TAG_FOLDER, strFolder); // Create the part. LayoutPart::Pointer part; if (strFolder.isEmpty()) { // this is the editor area part = new PartPlaceholder(partID); } else { PartStack::Pointer folder(new PartStack(page)); folder->SetID(partID); //result.add(folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER))); result &= folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER)); ContainerPlaceholder::Pointer placeholder(new ContainerPlaceholder(partID)); placeholder->SetRealContainer(folder); part = placeholder; } // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active part->SetContainer(ILayoutContainer::Pointer(this)); const int myLeft = left, myRight = right, myRelationship = relationship; LayoutPart::Pointer myPart = part; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.isEmpty()) { this->Add(myPart); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { this->Add(myPart, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = part; } return result; } bool ViewSashContainer::SaveState(IMemento::Pointer memento) { QList relationships = this->ComputeRelation(); bool result = true; // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, null); // Loop through the relationship array. for (int i = 0; i < relationships.size(); ++i) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); if (info.relative) { childMem->PutString(WorkbenchConstants::TAG_RELATIVE, info.relative->GetID()); childMem->PutInteger(WorkbenchConstants::TAG_RELATIONSHIP, info.relationship); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_LEFT, info.left); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_RIGHT, info.right); } // Is this part a folder or a placeholder for one? PartStack::Pointer folder(info.part.Cast()); if (!folder && info.part.Cast()) { LayoutPart::Pointer part = info.part.Cast()->GetRealContainer(); folder = part.Cast(); } // If this is a folder (PartStack) save the contents. if (folder) { childMem->PutString(WorkbenchConstants::TAG_FOLDER, "true"); IMemento::Pointer folderMem(childMem->CreateChild(WorkbenchConstants::TAG_FOLDER)); //result.add(folder.saveState(folderMem)); result = folder->SaveState(folderMem); } } return result; } bool ViewSashContainer::IsStackType(ILayoutContainer::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR); } bool ViewSashContainer::IsPaneType(LayoutPart::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool ViewSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } void ViewSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // Nasty hack: ensure that all views end up inside a tab folder. // Since the view title is provided by the tab folder, this ensures // that views don't get created without a title tab. if (newChild.Cast()) { PartStack::Pointer folder(new PartStack(page)); folder->Add(newChild); newChild = folder; } PartSashContainer::Replace(oldChild, newChild); } void* ViewSashContainer::CreateParent(void* parentWidget) { return parentWidget; } void ViewSashContainer::DisposeParent() { // do nothing } float ViewSashContainer::GetDockingRatio(Object::Pointer dragged, ILayoutContainer::Pointer target) { if (this->IsStackType(target)) { return PartSashContainer::GetDockingRatio(dragged, target); } else { return 0.25f; } } PartStack::Pointer ViewSashContainer::CreateStack() { PartStack::Pointer result(new PartStack(page)); return result; } void ViewSashContainer::SetVisiblePart(ILayoutContainer::Pointer container, PartPane::Pointer visiblePart) { if (container.Cast () != 0) { PartStack::Pointer tabFolder = container.Cast (); tabFolder->SetSelection(visiblePart); } } LayoutPart::Pointer ViewSashContainer::GetVisiblePart( ILayoutContainer::Pointer container) { return container.Cast ()->GetSelection(); } void ViewSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { page->GetActivePerspective()->GetPresentation()->DerefPart(sourcePart); } // void ViewSashContainer::AddChild(const RelationshipInfo& info) // { // LayoutPart child = info.part; // // // Nasty hack: ensure that all views end up inside a tab folder. // // Since the view title is provided by the tab folder, this ensures // // that views don't get created without a title tab. // if (child instanceof ViewPane) // { // ViewStack folder = new ViewStack(page); // folder.add(child); // info.part = folder; // } // // super.addChild(info); // } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSite.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSite.cpp index a8bee096ac..5db82bc497 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSite.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSite.cpp @@ -1,56 +1,55 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewSite.h" #include "berryIViewReference.h" #include "berryIViewPart.h" #include "berryPartPane.h" -#include "berryImageDescriptor.h" #include "berryViewDescriptor.h" #include "berryWorkbenchPage.h" namespace berry { ViewSite::ViewSite(IViewReference::Pointer ref, IViewPart::Pointer view, WorkbenchPage* page, const QString& id, const QString& pluginId, const QString& registeredName) : PartSite(ref, view, page) { SetId(id); SetRegisteredName(registeredName); SetPluginId(pluginId); } ViewSite::ViewSite(IViewReference::Pointer ref, IViewPart::Pointer view, WorkbenchPage* page, IViewDescriptor::Pointer desc) : PartSite(ref, view, page) { SetConfigurationElement(desc.Cast()->GetConfigurationElement()); } QString ViewSite::GetSecondaryId() { return GetPartReference().Cast()->GetSecondaryId(); } IViewPart::Pointer ViewSite::GetViewPart() { return GetPart().Cast(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp index 12128a8d10..3abe6841e1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp @@ -1,1869 +1,1868 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" #include "berryWorkbenchWindow.h" -#include "berryImageDescriptor.h" #include "berryDisplay.h" #include "services/berryIServiceFactory.h" #include "util/berrySafeRunnable.h" #include "berryWorkbenchServiceRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchMenuService.h" #include "berryEvaluationService.h" #include "berryCommandService.h" #include "berryCommandManager.h" #include "berryParameterType.h" #include "berrySourceProviderService.h" #include "berryWorkbenchLocationService.h" #include #include #include #include #include #include #include #include #include #include //#include //#include #include namespace berry { Workbench* Workbench::instance = 0; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const QString Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const QString Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const QString& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile.toStdString()), result(result) { } void Run() { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format QString version; memento->GetString(WorkbenchConstants::TAG_VERSION, version); bool valid = false; for (std::size_t i = 0; i < Workbench::VERSION_STRING_COUNT; i++) { if (Workbench::VERSION_STRING[i] == version) { valid = true; break; } } if (!valid) { input.close(); QString msg = "Invalid workbench state version. workbench.xml will be deleted"; QMessageBox::critical(NULL, "Restoring Problems", msg); stateFile.remove(); // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result = false; return; } // // Validate compatible version format // // We no longer support the release 1.0 format // if (VERSION_STRING[0].equals(version)) // { // reader.close(); // QString msg = "The saved user interface layout is in an " // "obsolete format and cannot be preserved. Your projects and files " // "will not be affected. Press OK to convert to the new format. Press " // "Cancel to exit with no changes."; // QList dlgLabels; // dlgLabels.push_back("Ok"); // dlgLabels.push_back("Cancel"); // IDialog::Pointer dlg = MessageDialog::CreateDialog(Shell::Pointer(0), // "Cannot Preserve Layout", 0, msg, IDialog::WARNING, dlgLabels, 0); // IDialog::ReturnCode ignoreSavedState = dlg->Open(); // // OK is the default // if (ignoreSavedState == IDialog::OK) // { // stateFile.remove(); // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, // // null); // result = false; // } // else // { // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_EXIT, msg, // // null); // result = false; // } // return; // } // Restore the saved state //final IStatus restoreResult = restoreState(memento); /*bool restoreResult =*/ workbench->RestoreState(memento); input.close(); // if (restoreResult.getSeverity() == IStatus.ERROR) { // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // StatusManager.getManager().handle(restoreResult, StatusManager.LOG); // } // }); // // } } void HandleException(const std::exception& e) { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // QString msg = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$ // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, e); result = false; stateFile.remove(); // }}); } private: void Handle(const std::exception& e) { SafeRunnable::HandleException(e); } }; int Workbench::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // create the workbench instance Workbench workbench(display, advisor); // run the workbench event loop int returnCode = workbench.RunUI(); return returnCode; } Display* Workbench::CreateDisplay() { // create the display Display* newDisplay = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDisplay(); // workaround for 1GEZ9UR and 1GF07HN //newDisplay.setWarnings(false); // Set the priority higher than normal so as to be higher // than the JobManager. //Poco::Thread::current()->setPriority(Poco::Thread::PRIO_HIGH); //initializeImages(); return newDisplay; } Workbench::ServiceLocatorOwner::ServiceLocatorOwner(Workbench* wb) : workbench(wb) { } void Workbench::ServiceLocatorOwner::Dispose() { QMessageBox::information( NULL, "Restart needed", "A required plug-in is no longer available and the Workbench needs " "to be restarted. You will be prompted to save if there is any unsaved work."); workbench->Close(PlatformUI::RETURN_RESTART, true); } Workbench::Workbench(Display* display, WorkbenchAdvisor* advisor) : commandManager(0), progressCount(-1) , serviceLocatorOwner(new ServiceLocatorOwner(this)) , largeUpdates(0), introManager(0), isStarting(true), isClosing(false) { poco_check_ptr(display) ; poco_check_ptr(advisor); // the reference count to the one and only workbench instance // is increased, so that temporary smart pointer to the workbench // do not delete it this->Register(); this->display = display; this->advisor = advisor; Workbench::instance = this; serviceLocatorCreator.reset(new ServiceLocatorCreator()); serviceLocatorCreator->Register(); this->serviceLocator = serviceLocatorCreator->CreateServiceLocator( NULL, NULL, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(serviceLocatorCreator.data()); workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WORKBENCH_SCOPE, this, NULL, NULL, 0)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); returnCode = PlatformUI::RETURN_UNSTARTABLE; } Display* Workbench::GetDisplay() { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->instance = 0; this->UnRegister(false); } Object* Workbench::GetService(const QString& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const QString& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { // // setup debug mode if required. // if (WorkbenchPlugin.getDefault().isDebugging()) { // WorkbenchPlugin.DEBUG = true; // ModalContext.setDebugMode(true); // } bool bail = false; // create workbench window manager //windowManager = new WindowManager(); IIntroRegistry* introRegistry = WorkbenchPlugin::GetDefault() ->GetIntroRegistry(); if (introRegistry->GetIntroCount() > 0) { //TODO Product support //IProduct product = Platform.getProduct(); //if (product != null) { introDescriptor = introRegistry ->GetIntroForProduct("").Cast(); //product.getId()); //} } // TODO Correctly order service initialization // there needs to be some serious consideration given to // the services, and hooking them up in the correct order evaluationService.reset(new EvaluationService()); evaluationService->Register(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { serviceLocator->RegisterService(evaluationService.data()); // } // }); // Initialize the activity support. //workbenchActivitySupport = new WorkbenchActivitySupport(); //activityHelper = ActivityPersistanceHelper.getInstance(); this->InitializeDefaultServices(); // initializeFonts(); // initializeColors(); // initializeApplicationColors(); // now that the workbench is sufficiently initialized, let the advisor // have a turn. advisor->InternalBasicInitialize(this->GetWorkbenchConfigurer()); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { StartSourceProviders(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // activateWorkbenchContext(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // createApplicationMenu(); // } // }); // attempt to restore a previous workbench state advisor->PreStartup(); if (!advisor->OpenWindows()) { bail = true; } if (bail) return false; //forceOpenPerspective(); return true; } bool Workbench::RestoreState() { //return false; if (!GetWorkbenchConfigurer()->GetSaveAndRestore()) { // QString msg = "This application does not save and restore previously saved state."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // Read the workbench state file. QString stateFile = GetWorkbenchStateFile(); // If there is no state file cause one to open. if (stateFile.isEmpty() || !QFile::exists(stateFile)) { // QString msg = "No previously saved state to restore."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // final IStatus result[] = { new Status(IStatus.OK, // WorkbenchPlugin.PI_WORKBENCH, IStatus.OK, "", null) }; //$NON-NLS-1$ bool result = true; ISafeRunnable::Pointer runnable(new RestoreStateRunnable(this, stateFile, result)); SafeRunner::Run(runnable); // ensure at least one window was opened //if (result[0].isOK() && windowManager.getWindows().length == 0) if (result && windowManager.GetWindowCount() == 0) { QString msg = "No windows restored."; // result[0] = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result &= false; } return result; } bool Workbench::RestoreState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.Workbench_problemsRestoring, null); bool result = true; const bool showProgress = false; //TODO restore state progress // final boolean showProgress = PrefUtil.getAPIPreferenceStore() // .getBoolean( // IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); try { /* * Restored windows will be set in the createdWindows field to be * used by the openWindowsAfterRestore() method */ if (!showProgress) { DoRestoreState(memento, result); } else { // Retrieve how many plug-ins were loaded while restoring the // workbench int lastProgressCount = -1; memento->GetInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, lastProgressCount); // If we don't know how many plug-ins were loaded last time, // assume we are loading half of the installed plug-ins. /*const std::size_t expectedProgressCount =*/ std::max(1, lastProgressCount == -1 ? WorkbenchPlugin::GetDefault()->GetBundleCount() / 2 : lastProgressCount); //TODO restore state progress // RunStartupWithProgress(expectedProgressCount, new Runnable() { // public void Run() { // DoRestoreState(memento, result); // } // }); } } catch (...) { OpenWindowsAfterRestore(); throw; } OpenWindowsAfterRestore(); return result; } void Workbench::DoRestoreState(IMemento::Pointer memento, bool& status) // final MultiStatus status) { IMemento::Pointer childMem; try { // UIStats.start(UIStats.RESTORE_WORKBENCH, "MRUList"); //$NON-NLS-1$ IMemento::Pointer mruMemento = memento ->GetChild(WorkbenchConstants::TAG_MRU_LIST); if (mruMemento) { // TODO restore editor history //status.add(getEditorHistory().restoreState(mruMemento)); } //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ } catch (...) { //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ throw; } // Restore advisor state. IMemento::Pointer advisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); if (advisorState) { //status.add(getAdvisor().restoreState(advisorState)); status &= GetAdvisor()->RestoreState(advisorState); } // Get the child windows. QList children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (int i = 0; i < children.size(); i++) { childMem = children[i]; WorkbenchWindow::Pointer newWindow; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow = NewWorkbenchWindow(); newWindow->Create(); // }}); createdWindows.push_back(newWindow); // allow the application to specify an initial perspective to open // @issue temporary workaround for ignoring initial perspective // String initialPerspectiveId = // getAdvisor().getInitialWindowPerspectiveId(); // if (initialPerspectiveId != null) { // IPerspectiveDescriptor desc = // getPerspectiveRegistry().findPerspectiveWithId(initialPerspectiveId); // result.merge(newWindow.restoreState(childMem, desc)); // } // add the window so that any work done in newWindow.restoreState // that relies on Workbench methods has windows to work with windowManager.Add(newWindow); // now that we've added it to the window manager we need to listen // for any exception that might hose us before we get a chance to // open it. If one occurs, remove the new window from the manager. // Assume that the new window is a phantom for now try { //status.merge(newWindow[0].restoreState(childMem, null)); status &= newWindow->RestoreState(childMem, IPerspectiveDescriptor::Pointer(0)); try { newWindow->FireWindowRestored(); } catch (const WorkbenchException& /*e*/) { //status.add(e.getStatus()); status &= false; } // everything worked so far, don't close now } catch (...) { // null the window in newWindowHolder so that it won't be // opened later on createdWindows[i] = 0; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newWindow->Close(); // }}); } } } void Workbench::OpenWindowsAfterRestore() { if (createdWindows.empty()) { return; } // now open the windows (except the ones that were nulled because we // closed them above) for (int i = 0; i < createdWindows.size(); i++) { if (createdWindows[i]) { WorkbenchWindow::Pointer myWindow = createdWindows[i]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { try { myWindow->Open(); } catch (...) { myWindow->Close(); throw; } // }}); } } createdWindows.clear(); } void Workbench::InitializeDefaultServices() { // final IContributionService contributionService = new ContributionService( // getAdvisor()); // serviceLocator.registerService(IContributionService.class, // contributionService); // // // TODO Correctly order service initialization // // there needs to be some serious consideration given to // // the services, and hooking them up in the correct order // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { saveablesList.reset(new SaveablesList()); saveablesList->Register(); serviceLocator->RegisterService(saveablesList.data()); // }}); // /* * Phase 1 of the initialization of commands. When this phase completes, * all the services and managers will exist, and be accessible via the * getService(Object) method. */ // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // Command.DEBUG_COMMAND_EXECUTION = Policy.DEBUG_COMMANDS; commandManager.reset(new CommandManager()); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { commandService.reset(new CommandService(commandManager.data())); commandService->Register(); commandService->ReadRegistry(); serviceLocator->RegisterService(commandService.data()); // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // ContextManager.DEBUG = Policy.DEBUG_CONTEXTS; // contextManager = new ContextManager(); // }}); // // final IContextService contextService = new ContextService( // contextManager); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // contextService.readRegistry(); // }}); // // serviceLocator.registerService(IContextService.class, contextService); // // // final IBindingService [] bindingService = new BindingService[1]; // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS; // bindingManager = new BindingManager(contextManager, commandManager); // bindingService[0] = new BindingService( // bindingManager, commandService[0], Workbench.this); // // }}); // // bindingService[0].readRegistryAndPreferences(commandService[0]); // serviceLocator.registerService(IBindingService.class, bindingService[0]); // // final CommandImageManager commandImageManager = new CommandImageManager(); // final CommandImageService commandImageService = new CommandImageService( // commandImageManager, commandService[0]); // commandImageService.readRegistry(); // serviceLocator.registerService(ICommandImageService.class, // commandImageService); WorkbenchMenuService* wms = new WorkbenchMenuService(serviceLocator.GetPointer()); menuService.reset(wms); menuService->Register(); serviceLocator->RegisterService(menuService.data()); // the service must be registered before it is initialized - its // initialization uses the service locator to address a dependency on // the menu service //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { wms->ReadRegistry(); // }}); // the source providers are now initialized in phase 3, but source // priorities have to be set before handler initialization // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { InitializeSourcePriorities(); // } // }); /* * Phase 2 of the initialization of commands. This handles the creation * of wrappers for legacy APIs. By the time this phase completes, any * code trying to access commands through legacy APIs should work. */ //IHandlerService* handlerService = NULL; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { /*handlerService = */serviceLocator->GetService(); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); // addWindowListener(windowListener); // bindingManager.addBindingManagerListener(bindingManagerListener); // serviceLocator.registerService(ISelectionConversionService.class, // new SelectionConversionService()); } int Workbench::RunUI() { // initialize workbench and restore or open one window bool initOK = this->Init(); // let the advisor run its start up code if (initOK) { advisor->PostStartup(); // may trigger a close/restart } //TODO start eager plug-ins //startPlugins(); //addStartupRegistryListener(); isStarting = false; BERRY_INFO << "BlueBerry Workbench ready"; this->GetWorkbenchTestable()->Init(Display::GetDefault(), this); // spin event loop return display->RunEventLoop(); } QString Workbench::GetDefaultPerspectiveId() { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } IAdaptable* Workbench::GetDefaultPageInput() { return this->GetAdvisor()->GetDefaultPageInput(); } QString Workbench::GetPresentationId() { if (factoryID != "") { return factoryID; } //factoryID = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID); // Workaround for bug 58975 - New preference mechanism does not properly // initialize defaults // Ensure that the UI plugin has started too. factoryID = WorkbenchConstants::DEFAULT_PRESENTATION_ID; return factoryID; } void Workbench::UpdateTheme() { WorkbenchPlugin::GetDefault()->GetPresentationFactory()->UpdateTheme(); } void Workbench::LargeUpdateStart() { if (largeUpdates++ == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(false); // workbenchContextSupport.setProcessing(false); QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateStart(); } } } } void Workbench::LargeUpdateEnd() { if (--largeUpdates == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(true); // workbenchContextSupport.setProcessing(true); // Perform window-specific blocking. QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } void Workbench::OpenFirstTimeWindow() { try { IAdaptable* input; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { input = this->GetDefaultPageInput(); // }}); this->BusyOpenWorkbenchWindow(this->GetPerspectiveRegistry()->GetDefaultPerspective(), input); } catch (WorkbenchException& e) { // Don't use the window's shell as the dialog parent, // as the window is not open yet (bug 76724). //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Problems_Opening_Page, e.getMessage(), e // .getStatus()); // }}); BERRY_ERROR << "Error: Problems opening page. " << e.what() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } WorkbenchAdvisor* Workbench::GetAdvisor() { return advisor; } IViewRegistry* Workbench::GetViewRegistry() { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } IEditorRegistry* Workbench::GetEditorRegistry() { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() { return WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry(); } bool Workbench::Close() { return this->Close(PlatformUI::RETURN_OK, false); } bool Workbench::Close(int returnCode, bool force) { BERRY_INFO << "Closing workbench..."; this->returnCode = returnCode; bool ret; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(force); // } //}); return ret; } /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool Workbench::BusyClose(bool force) { // notify the advisor of preShutdown and allow it to veto if not forced isClosing = advisor->PreShutdown(); if (!force && !isClosing) { return false; } // notify regular workbench clients of preShutdown and allow them to // veto if not forced isClosing = this->FirePreShutdown(force); if (!force && !isClosing) { return false; } // save any open editors if they are dirty isClosing = this->SaveAllEditors(!force); if (!force && !isClosing) { return false; } bool closeEditors = !force && false; // false is the default for the not yet implemented preference below // && PrefUtil.getAPIPreferenceStore().getBoolean( // IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT); if (closeEditors) { // SafeRunner.run(new SafeRunnable() { // public void run() { QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchPage::Pointer page = windows[i]->GetActivePage(); if (page) isClosing = isClosing && page->CloseAllEditors(false); } // } //}); if (!force && !isClosing) { return false; } } if (this->GetWorkbenchConfigurer()->GetSaveAndRestore()) { try { // SafeRunner.run(new SafeRunnable() { // public void run() { XMLMemento::Pointer mem = RecordWorkbenchState(); // Save the IMemento to a file. SaveMementoToFile(mem); // } } catch(const ctkException& e) { // public void handleException(Throwable e) { QString message; if (e.what() == 0) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = QString("An error has occurred: ") + e.what() + ". See error log for more details. Do you want to exit?"; } if (QMessageBox::question(NULL, "Error", message) != QMessageBox::Yes) { isClosing = false; } } // } // }); } if (!force && !isClosing) { return false; } //SafeRunner.run(new SafeRunnable(WorkbenchMessages.ErrorClosing) { // public void run() { if (isClosing || force) { isClosing = windowManager.Close(); } // } //}); if (!force && !isClosing) { return false; } this->Shutdown(); display->ExitEventLoop(0); return true; } QString Workbench::GetWorkbenchStateFile() const { QString path = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (path.isNull()) { return QString(); } return QDir::cleanPath(path + "/" + DEFAULT_WORKBENCH_STATE_FILENAME); } /* * Save the workbench UI in a persistence file. */ bool Workbench::SaveMementoToFile(XMLMemento::Pointer memento) { // Save it to a file. // XXX: nobody currently checks the return value of this method. QString stateFile = GetWorkbenchStateFile(); if (stateFile.isNull()) { return false; } //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.toStdString()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { QFile::remove(stateFile); QMessageBox::critical(NULL, "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() const { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } std::size_t Workbench::GetWorkbenchWindowCount() { return windowManager.GetWindowCount(); } QList Workbench::GetWorkbenchWindows() { QList windows = windowManager.GetWindows(); QList result; for (QList::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Run op in busy cursor. //final Object[] result = new Object[1]; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { return this->BusyOpenWorkbenchWindow(perspID, input); // } catch (WorkbenchException e) { // result[0] = e; // } // } //}); } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow(IAdaptable* input) { return this->OpenWorkbenchWindow(this->GetPerspectiveRegistry() ->GetDefaultPerspective(), input); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& perspectiveId, IWorkbenchWindow::Pointer window) { // If the specified window has the requested perspective open, then the // window // is given focus and the perspective is shown. The page's input is // ignored. WorkbenchWindow::Pointer win = window.Cast (); if (win) { IWorkbenchPage::Pointer page = win->GetActivePage(); if (page) { QList perspectives(page ->GetOpenPerspectives()); for (int i = 0; i < perspectives.size(); i++) { IPerspectiveDescriptor::Pointer persp = perspectives[i]; if (perspectiveId == persp->GetId()) { win->MakeVisible(); page->SetPerspective(persp); return page; } } } } // If another window that has the workspace root as input and the // requested // perpective open and active, then the window is given focus. IAdaptable* input = GetDefaultPageInput(); QList windows(GetWorkbenchWindows()); for (int i = 0; i < windows.size(); i++) { win = windows[i].Cast(); if (window != win) { WorkbenchPage::Pointer page = win->GetActivePage().Cast(); if (page) { bool inputSame = false; if (input == 0) { inputSame = (page->GetInput() == 0); } else { inputSame = input == page->GetInput(); } if (inputSame) { Perspective::Pointer persp = page->GetActivePerspective(); if (persp) { IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc) { if (perspectiveId == desc->GetId()) { Shell::Pointer shell = win->GetShell(); shell->Open(); if (shell->GetMinimized()) { shell->SetMinimized(false); } return page; } } } } } } } // Otherwise the requested perspective is opened and shown in the // specified // window or in a new window depending on the current user preference // for opening // perspectives, and that window is given focus. win = window.Cast(); if (win) { IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); int mode = store->GetSystemPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = win->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page) { persp = page->GetPerspective(); } // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp) { IWorkbenchWindow::Pointer newWindow = OpenWorkbenchWindow(perspectiveId, input); return newWindow->GetActivePage(); } IPerspectiveDescriptor::Pointer desc = GetPerspectiveRegistry() ->FindPerspectiveWithId(perspectiveId); if (desc == 0) { throw WorkbenchException( "Unable to create perspective \"" + perspectiveId + "\". There is no corresponding perspective extension."); } win->GetShell()->Open(); if (page == 0) { page = win->OpenPage(perspectiveId, input); } else { page->SetPerspective(desc); } return page; } // Just throw an exception.... throw WorkbenchException("Problems opening perspective \"" + perspectiveId + "\""); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& /*perspectiveId*/, IWorkbenchWindow::Pointer /*window*/, IAdaptable* /*input*/) { return IWorkbenchPage::Pointer(0); // // If the specified window has the requested perspective open and the // // same requested // // input, then the window is given focus and the perspective is shown. // bool inputSameAsWindow = false; // WorkbenchWindow::Pointer win = window.Cast(); // if (win.IsNotNull()) { // WorkbenchPage::Pointer page = win->GetActiveWorkbenchPage(); // if (page.IsNotNull()) { // bool inputSame = false; // if (input == 0) { // inputSame = (page->GetInput() == 0); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // inputSameAsWindow = true; // IPerspectiveDescriptor perspectives[] = page // .getOpenPerspectives(); // for (int i = 0; i < perspectives.length; i++) { // IPerspectiveDescriptor persp = perspectives[i]; // if (perspectiveId.equals(persp.getId())) { // win.makeVisible(); // page.setPerspective(persp); // return page; // } // } // } // } // } // // // If another window has the requested input and the requested // // perpective open and active, then that window is given focus. // IWorkbenchWindow[] windows = getWorkbenchWindows(); // for (int i = 0; i < windows.length; i++) { // win = (WorkbenchWindow) windows[i]; // if (window != win) { // WorkbenchPage page = win.getActiveWorkbenchPage(); // if (page != null) { // boolean inputSame = false; // if (input == null) { // inputSame = (page.getInput() == null); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // Perspective persp = page.getActivePerspective(); // if (persp != null) { // IPerspectiveDescriptor desc = persp.getDesc(); // if (desc != null) { // if (perspectiveId.equals(desc.getId())) { // win.getShell().open(); // return page; // } // } // } // } // } // } // } // // // If the specified window has the same requested input but not the // // requested // // perspective, then the window is given focus and the perspective is // // opened and shown // // on condition that the user preference is not to open perspectives in // // a new window. // win = (WorkbenchWindow) window; // if (inputSameAsWindow && win != null) { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int mode = store.getInt(IPreferenceConstants.OPEN_PERSP_MODE); // // if (IPreferenceConstants.OPM_NEW_WINDOW != mode) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // If the specified window has no active perspective, then open the // // requested perspective and show the specified window. // if (win != null) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor persp = null; // if (page != null) { // persp = page.getPerspective(); // } // if (persp == null) { // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // Otherwise the requested perspective is opened and shown in a new // // window, and the // // window is given focus. // IWorkbenchWindow newWindow = openWorkbenchWindow(perspectiveId, input); // return newWindow.getActivePage(); } bool Workbench::SaveAllEditors(bool /*confirm*/) { return true; } IIntroManager* Workbench::GetIntroManager() { return GetWorkbenchIntroManager(); } WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() { if (introManager.isNull()) { introManager.reset(new WorkbenchIntroManager(this)); } return introManager.data(); } IntroDescriptor::Pointer Workbench::GetIntroDescriptor() const { return introDescriptor; } void Workbench::SetIntroDescriptor(IntroDescriptor::Pointer descriptor) { if (GetIntroManager()->GetIntro()) { GetIntroManager()->CloseIntro(GetIntroManager()->GetIntro()); } introDescriptor = descriptor; } bool Workbench::IsRunning() { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } bool Workbench::IsStarting() { return isStarting; } bool Workbench::IsClosing() { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() const { return activatedWindow; } /* * Sets the workbench window which was last known being the active one, or * null . */ void Workbench::SetActivatedWindow(WorkbenchWindow::Pointer window) { activatedWindow = window; } WorkbenchWindow::Pointer Workbench::NewWorkbenchWindow() { WorkbenchWindow::Pointer wbw(new WorkbenchWindow(this->GetNewWindowNumber())); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. QList windows = windowManager.GetWindows(); int count = static_cast(windows.size()); // Create an array of booleans (size = window count). // Cross off every number found in the window list. bool *checkArray = new bool[count]; for (int nX = 0; nX < count; ++nX) { if (windows[nX].Cast ().IsNotNull()) { WorkbenchWindow::Pointer ww = windows[nX].Cast (); int index = ww->GetNumber() - 1; if (index >= 0 && index < count) { checkArray[index] = true; } } } // Return first index which is not used. // If no empty index was found then every slot is full. // Return next index. for (int index = 0; index < count; index++) { if (!checkArray[index]) { delete[] checkArray; return index + 1; } } delete[] checkArray; return static_cast(count + 1); } IWorkbenchWindow::Pointer Workbench::BusyOpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Create a workbench window (becomes active window) //final WorkbenchWindow newWindowArray[] = new WorkbenchWindow[1]; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { // newWindowArray[0] = newWorkbenchWindow(); WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); // } //}); //final WorkbenchWindow newWindow = newWindowArray[0]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Create(); // must be created before adding to window // manager // } //}); windowManager.Add(newWindow); //final WorkbenchException [] exceptions = new WorkbenchException[1]; // Create the initial page. if (perspID != "") { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { try { newWindow->BusyOpenPage(perspID, input); } catch (WorkbenchException& e) { windowManager.Remove(newWindow); throw e; } } // Open window after opening page, to avoid flicker. //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Open(); // } //}); return newWindow; } bool Workbench::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Workbench_problemsSaving, null); bool result = true; // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING[0]); // Save how many plug-ins were loaded while restoring the workbench if (progressCount != -1) { memento->PutInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, progressCount); } // Save the advisor state. IMemento::Pointer advisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); //result.add(getAdvisor().saveState(advisorState)); result &= GetAdvisor()->SaveState(advisorState); // Save the workbench windows. QList windows(GetWorkbenchWindows()); for (int nX = 0; nX < windows.size(); nX++) { WorkbenchWindow::Pointer window = windows[nX].Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_WINDOW); //result.merge(window.saveState(childMem)); result &= window->SaveState(childMem); } // result.add(getEditorHistory().saveState( // memento.createChild(IWorkbenchConstants.TAG_MRU_LIST))); return result; } XMLMemento::Pointer Workbench::RecordWorkbenchState() { XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_WORKBENCH); //final IStatus status = saveState(memento); bool status = SaveState(memento); //if (status.getSeverity() != IStatus.OK) { if (!status) { // // don't use newWindow as parent because it has not yet been opened // // (bug 76724) // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Workbench_problemsSaving, // WorkbenchMessages.Workbench_problemsSavingMsg, status); // }}); } return memento; } void Workbench::AddWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener* l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener* l) { windowEvents.RemoveListener(l); } IWindowListener::Events& Workbench::GetWindowEvents() { return windowEvents; } bool Workbench::FirePreShutdown(bool forced) { //SafeRunnable.run(new SafeRunnable() { // public void run() { typedef IWorkbenchListener::Events::PreShutdownEvent::ListenerList ListenerList; const ListenerList& listeners = workbenchEvents.preShutdown.GetListeners(); for ( ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter ) { // notify each listener if (! (*iter)->Execute(dynamic_cast(this), forced)) return false; } // } return true; } /** * Fire workbench postShutdown event. * * @since 3.2 */ void Workbench::FirePostShutdown() { // SafeRunnable.run(new SafeRunnable() { // public void run() { workbenchEvents.postShutdown(this); // } } void Workbench::FireWindowOpened(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowOpened(window); // } } void Workbench::FireWindowClosed(IWorkbenchWindow::Pointer window) { if (activatedWindow == window) { // Do not hang onto it so it can be GC'ed activatedWindow = 0; } // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowClosed(window); // } } void Workbench::FireWindowActivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowActivated(window); // } } void Workbench::FireWindowDeactivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowDeactivated(window); // } } IWorkbenchWindow::Pointer Workbench::RestoreWorkbenchWindow(IMemento::Pointer memento) { WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); //newWindow.create(); windowManager.Add(newWindow); // whether the window was opened bool opened = false; try { newWindow->RestoreState(memento, IPerspectiveDescriptor::Pointer(0)); newWindow->FireWindowRestored(); newWindow->Open(); opened = true; } catch (...) { if (!opened) { newWindow->Close(); } } return newWindow; } void Workbench::Shutdown() { // shutdown application-specific portions first advisor->PostShutdown(); // notify regular workbench clients of shutdown, and clear the list when // done this->FirePostShutdown(); //workbenchListeners.clear(); //cancelEarlyStartup(); // for dynamic UI // Platform.getExtensionRegistry().removeRegistryChangeListener( // extensionEventHandler); // Platform.getExtensionRegistry().removeRegistryChangeListener( // startupRegistryListener); // ((GrabFocus) Tweaklets.get(GrabFocus.KEY)).dispose(); // Bring down all of the services. serviceLocator->Dispose(); // workbenchActivitySupport.dispose(); // WorkbenchHelpSystem.disposeIfNecessary(); // shutdown the rest of the workbench // WorkbenchColors.shutdown(); // activityHelper.shutdown(); // uninitializeImages(); // if (WorkbenchPlugin.getDefault() != null) { // WorkbenchPlugin.getDefault().reset(); // } // WorkbenchThemeManager.getInstance().dispose(); // PropertyPageContributorManager.getManager().dispose(); // ObjectActionContributorManager.getManager().dispose(); // if (tracker != null) { // tracker.close(); // } Tweaklets::Clear(); } void Workbench::InitializeSourcePriorities() { WorkbenchServiceRegistry::GetRegistry()->InitializeSourcePriorities(); } void Workbench::StartSourceProviders() { /* * Phase 3 of the initialization of commands. The source providers that * the workbench provides are creating and registered with the above * services. These source providers notify the services when particular * pieces of workbench state change. */ IEvaluationService* const evaluationService = serviceLocator->GetService(); //IContextService* const contextService = serviceLocator->GetService(); SourceProviderService* sps = new SourceProviderService(serviceLocator.GetPointer()); sourceProviderService.reset(sps); sourceProviderService->Register(); serviceLocator->RegisterService(sourceProviderService.data()); struct SafeSourceProviderRunnable : public ISafeRunnable { SafeSourceProviderRunnable(SourceProviderService* sps, IEvaluationService* es) : sps(sps), es(es) {} void Run() { // this currently instantiates all players ... sigh sps->ReadRegistry(); QList sp = sps->GetSourceProviders(); for (int i = 0; i < sp.size(); i++) { es->AddSourceProvider(sp[i]); //if (!(sp[i] instanceof ActiveContextSourceProvider)) //{ // contextService.addSourceProvider(sp[i]); //} } } void HandleException(const std::exception& exception) { WorkbenchPlugin::Log("Failed to initialize a source provider", ctkException(QString(exception.what()))); } private: SourceProviderService* sps; IEvaluationService* es; }; ISafeRunnable::Pointer sourceProviderRunnable( new SafeSourceProviderRunnable(sps, evaluationService)); SafeRunner::Run(sourceProviderRunnable); // SafeRunner.run(new ISafeRunnable() { // public void run() throws Exception { // // these guys are need to provide the variables they say // // they source // actionSetSourceProvider = (ActionSetSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_ACTION_SETS_NAME); // FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME); // serviceLocator.registerService(IFocusService.class, focusControl); // menuSourceProvider = (MenuSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_MENU_NAME); // } // public void handleException(Throwable exception) { // WorkbenchPlugin.log("Failed to initialize a source provider", exception); //$NON-NLS-1$ // } // }); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchConfigurer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchConfigurer.cpp index 6be6472a10..d9b80bfc44 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchConfigurer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchConfigurer.cpp @@ -1,131 +1,130 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchConfigurer.h" #include "berryPlatformUI.h" #include "berryWorkbenchWindow.h" -#include "berryImageDescriptor.h" #include "berryWorkbench.h" namespace berry { WorkbenchConfigurer::WorkbenchConfigurer() : saveAndRestore(false), isEmergencyClosing(false), exitOnLastWindowClose(true) { } IWorkbench* WorkbenchConfigurer::GetWorkbench() { return PlatformUI::GetWorkbench(); } IWorkbenchWindowConfigurer::Pointer WorkbenchConfigurer::GetWindowConfigurer( IWorkbenchWindow::Pointer window) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } return window.Cast ()->GetWindowConfigurer(); } bool WorkbenchConfigurer::GetSaveAndRestore() { return saveAndRestore; } void WorkbenchConfigurer::SetSaveAndRestore(bool enabled) { saveAndRestore = enabled; } Object::Pointer WorkbenchConfigurer::GetData(const QString& key) const { if (key.isEmpty()) { throw Poco::InvalidArgumentException(); } QHash::ConstIterator i = extraData.find(key); if (i != extraData.end()) return i.value(); return Object::Pointer(0); } void WorkbenchConfigurer::SetData(const QString& key, Object::Pointer data) { if (key.isEmpty()) { throw ctkInvalidArgumentException("Key must not be empty"); } if (data) { extraData.insert(key, data); } else { extraData.remove(key); } } void WorkbenchConfigurer::EmergencyClose() { if (!isEmergencyClosing) { isEmergencyClosing = true; if (Workbench::GetInstance() != 0 && !Workbench::GetInstance()->IsClosing()) { Workbench::GetInstance()->Close(PlatformUI::RETURN_EMERGENCY_CLOSE, true); } } } bool WorkbenchConfigurer::EmergencyClosing() { return isEmergencyClosing; } bool WorkbenchConfigurer::RestoreState() { return dynamic_cast (GetWorkbench())->RestoreState(); } void WorkbenchConfigurer::OpenFirstTimeWindow() { dynamic_cast (this->GetWorkbench())->OpenFirstTimeWindow(); } IWorkbenchWindowConfigurer::Pointer WorkbenchConfigurer::RestoreWorkbenchWindow( IMemento::Pointer memento) { return this->GetWindowConfigurer( dynamic_cast (this->GetWorkbench())->RestoreWorkbenchWindow( memento)); } bool WorkbenchConfigurer::GetExitOnLastWindowClose() { return exitOnLastWindowClose; } void WorkbenchConfigurer::SetExitOnLastWindowClose(bool enabled) { exitOnLastWindowClose = enabled; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp index f546bede34..c0ec3d0423 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp @@ -1,4105 +1,4104 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartSite.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPerspective.h" #include "berryLayoutPartSash.h" #include "berryWorkbenchPlugin.h" #include "berryEditorAreaHelper.h" #include "berrySaveablesList.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTreeNode.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartService.h" #include "berryStickyViewManager.h" #include "intro/berryIntroConstants.h" #include "intro/berryViewIntroAdapterPart.h" #include "berryWorkbenchWindow.h" #include "berryUIException.h" #include "berryPlatformUI.h" #include "berryPartPane.h" -#include "berryImageDescriptor.h" #include #include namespace berry { WorkbenchPage::ActivationOrderPred::ActivationOrderPred( WorkbenchPage::ActivationList* al) : activationList(al) { } bool WorkbenchPage::ActivationOrderPred::operator()( const IViewReference::Pointer o1, const IViewReference::Pointer o2) const { WorkbenchPage::ActivationList::PartListIter pos1 = activationList->IndexOf( o1.Cast ()); WorkbenchPage::ActivationList::PartListIter pos2 = activationList->IndexOf( o2.Cast ()); return pos1 < pos2; } void WorkbenchPage::PerspectiveList::UpdateActionSets( Perspective::Pointer /*oldPersp*/, Perspective::Pointer /*newPersp*/) { //TODO WorkbenchPage action sets // // Update action sets // // IContextService service = (IContextService) window // .getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // if (newPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = newPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.showAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = newPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.maskAction(descriptor); // } // } // // if (oldPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = oldPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.hideAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = oldPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.unmaskAction(descriptor); // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } } WorkbenchPage::PerspectiveList::PerspectiveList() { } void WorkbenchPage::PerspectiveList::Reorder( IPerspectiveDescriptor::Pointer perspective, int newLoc) { PerspectiveListType::iterator oldLocation = openedList.end(); Perspective::Pointer movedPerspective; for (PerspectiveListType::iterator iterator = openedList.begin(); iterator != openedList.end(); ++iterator) { Perspective::Pointer openPerspective = *iterator; if (openPerspective->GetDesc() == perspective) { oldLocation = std::find(openedList.begin(), openedList.end(), openPerspective); movedPerspective = openPerspective; } } PerspectiveListType::iterator newLocation = openedList.begin(); for (int i = 0; i < newLoc; ++i, ++newLocation) ; if (oldLocation == newLocation) { return; } openedList.erase(oldLocation); openedList.insert(newLocation, movedPerspective); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetSortedPerspectives() { return usedList; } bool WorkbenchPage::PerspectiveList::Add(Perspective::Pointer perspective) { openedList.push_back(perspective); usedList.push_front(perspective); //It will be moved to top only when activated. return true; } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::Begin() { return openedList.begin(); } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::End() { return openedList.end(); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetOpenedPerspectives() { return openedList; } bool WorkbenchPage::PerspectiveList::Remove(Perspective::Pointer perspective) { if (active == perspective) { this->UpdateActionSets(active, Perspective::Pointer(0)); active = 0; } usedList.removeAll(perspective); PerspectiveListType::size_type origSize = openedList.size(); openedList.removeAll(perspective); return openedList.size() != origSize; } void WorkbenchPage::PerspectiveList::Swap(Perspective::Pointer oldPerspective, Perspective::Pointer newPerspective) { PerspectiveListType::iterator oldIter = std::find(openedList.begin(), openedList.end(), oldPerspective); PerspectiveListType::iterator newIter = std::find(openedList.begin(), openedList.end(), newPerspective); if (oldIter == openedList.end() || newIter == openedList.end()) { return; } std::iter_swap(oldIter, newIter); } bool WorkbenchPage::PerspectiveList::IsEmpty() { return openedList.empty(); } Perspective::Pointer WorkbenchPage::PerspectiveList::GetActive() { return active; } Perspective::Pointer WorkbenchPage::PerspectiveList::GetNextActive() { if (active == 0) { if (usedList.empty()) { return Perspective::Pointer(0); } else { return usedList.back(); } } else { if (usedList.size() < 2) { return Perspective::Pointer(0); } else { return *(--usedList.end()); } } } WorkbenchPage::PerspectiveList::PerspectiveListType::size_type WorkbenchPage::PerspectiveList::Size() { return openedList.size(); } void WorkbenchPage::PerspectiveList::SetActive(Perspective::Pointer perspective) { if (perspective == active) { return; } this->UpdateActionSets(active, perspective); active = perspective; if (perspective != 0) { usedList.removeAll(perspective); usedList.push_back(perspective); } } WorkbenchPage::ActivationList::ActivationList(WorkbenchPage* page) : page(page) { } void WorkbenchPage::ActivationList::SetActive(SmartPointer part) { if (parts.empty()) { return; } IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref) { if (ref == parts.back()) { return; } parts.erase(std::find(parts.begin(), parts.end(), ref)); parts.push_back(ref); } } void WorkbenchPage::ActivationList::BringToTop(SmartPointer< IWorkbenchPartReference> ref) { ILayoutContainer::Pointer targetContainer(page->GetContainer(ref)); PartListIter newIndex = this->LastIndexOfContainer(targetContainer); if (newIndex != parts.end() && ref == *newIndex) { return; } if (newIndex == parts.end()) { parts.push_back(ref); } else { PartListType::size_type index = newIndex - parts.begin(); parts.erase(std::find(parts.begin(), parts.end(), ref)); PartListIter insertIndex = parts.begin() + index; parts.insert(insertIndex, ref); } } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::LastIndexOfContainer( SmartPointer container) { PartListReverseIter i = parts.rbegin(); while (i != parts.rend()) { IWorkbenchPartReference::Pointer ref(*i); ILayoutContainer::Pointer cnt(page->GetContainer(ref)); if (cnt == container) { return --i.base(); } ++i; } return parts.end(); } void WorkbenchPage::ActivationList::SetActive(SmartPointer< IWorkbenchPartReference> ref) { this->SetActive(ref->GetPart(true)); } void WorkbenchPage::ActivationList::Add( SmartPointer ref) { if (std::find(parts.begin(), parts.end(), ref) != parts.end()) { return; } ref->GetPart(false); parts.push_front(ref); } SmartPointer WorkbenchPage::ActivationList::GetActive() { if (parts.empty()) { return IWorkbenchPart::Pointer(0); } return this->GetActive(parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetPreviouslyActive() { if (parts.size() < 2) { return IWorkbenchPart::Pointer(0); } return this->GetActive(--parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( bool editorsOnly) { return this->GetActiveReference(parts.end(), editorsOnly); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer part) { IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref == 0) { return parts.end(); } return std::find(parts.begin(), parts.end(), ref); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer ref) { return std::find(parts.begin(), parts.end(), ref); } bool WorkbenchPage::ActivationList::Remove( SmartPointer ref) { bool contains = std::find(parts.begin(), parts.end(), ref) != parts.end(); parts.erase(std::find(parts.begin(), parts.end(), ref)); return contains; } SmartPointer WorkbenchPage::ActivationList::GetTopEditor() { IEditorReference::Pointer editor = this->GetActiveReference(parts.end(), true).Cast (); if (editor == 0) { return IEditorPart::Pointer(0); } return editor->GetEditor(true); } SmartPointer WorkbenchPage::ActivationList::GetActive( PartListIter start) { IWorkbenchPartReference::Pointer ref(this->GetActiveReference(start, false)); if (!ref) { return IWorkbenchPart::Pointer(0); } return ref->GetPart(true); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly) { // First look for parts that aren't obscured by the current zoom state IWorkbenchPartReference::Pointer nonObscured = this->GetActiveReference( start, editorsOnly, true); if (nonObscured) { return nonObscured; } // Now try all the rest of the parts return this->GetActiveReference(start, editorsOnly, false); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly, bool /*skipPartsObscuredByZoom*/) { QList views = page->GetViewReferences(); PartListReverseIter i(start); while (i != parts.rend()) { WorkbenchPartReference::Pointer ref(i->Cast ()); if (editorsOnly && (ref.Cast () == 0)) { ++i; continue; } // Skip parts whose containers have disabled auto-focus PartPane::Pointer pane(ref->GetPane()); if (pane) { if (!pane->AllowsAutoFocus()) { ++i; continue; } // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } } // Skip fastviews (unless overridden) if (IViewReference::Pointer viewRef = ref.Cast()) { //if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { for (int j = 0; j < views.size(); j++) { if (views[j] == viewRef) { return viewRef.Cast (); } } //} } else { return ref.Cast (); } ++i; } return IWorkbenchPartReference::Pointer(0); } QList > WorkbenchPage::ActivationList::GetEditors() { QList editors; for (PartListIter i = parts.begin(); i != parts.end(); ++i) { if (IEditorReference::Pointer part = i->Cast()) { editors.push_back(part); } } return editors; } QList > WorkbenchPage::ActivationList::GetParts() { QList views(page->GetViewReferences()); QList resultList; for (PartListIter iterator = parts.begin(); iterator != parts.end(); ++iterator) { if (IViewReference::Pointer ref = iterator->Cast()) { //Filter views from other perspectives for (int i = 0; i < views.size(); i++) { if (ref == views[i]) { resultList.push_back(ref); break; } } } else { resultList.push_back(*iterator); } } return resultList; } void WorkbenchPage::ActionSwitcher::UpdateActivePart( IWorkbenchPart::Pointer newPart) { IWorkbenchPart::Pointer _activePart = this->activePart.Lock(); IEditorPart::Pointer _topEditor = this->topEditor.Lock(); if (_activePart == newPart) { return; } bool isNewPartAnEditor = newPart.Cast ().IsNotNull(); if (isNewPartAnEditor) { QString oldId; if (_topEditor) { oldId = _topEditor->GetSite()->GetId(); } QString newId = newPart->GetSite()->GetId(); // if the active part is an editor and the new editor // is the same kind of editor, then we don't have to do // anything if (activePart == topEditor && newId == oldId) { activePart = newPart; topEditor = newPart.Cast (); return; } // remove the contributions of the old editor // if it is a different kind of editor if (oldId != newId) { this->DeactivateContributions(_topEditor, true); } // if a view was the active part, disable its contributions if (_activePart && _activePart != _topEditor) { this->DeactivateContributions(_activePart, true); } // show (and enable) the contributions of the new editor // if it is a different kind of editor or if the // old active part was a view if (newId != oldId || _activePart != _topEditor) { this->ActivateContributions(newPart, true); } } else if (newPart.IsNull()) { if (_activePart) { // remove all contributions this->DeactivateContributions(_activePart, true); } } else { // new part is a view // if old active part is a view, remove all contributions, // but if old part is an editor only disable if (_activePart) { this->DeactivateContributions(_activePart, _activePart.Cast ().IsNotNull()); } this->ActivateContributions(newPart, true); } //TODO WorkbenchPage action sets // ArrayList newActionSets = 0; // if (isNewPartAnEditor || (activePart == topEditor && newPart == 0)) // { // newActionSets = calculateActionSets(newPart, 0); // } // else // { // newActionSets = calculateActionSets(newPart, topEditor); // } // // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } if (isNewPartAnEditor) { topEditor = newPart.Cast (); } else if (activePart == topEditor && newPart.IsNull()) { // since we removed all the contributions, we clear the top // editor topEditor.Reset(); } activePart = newPart; } void WorkbenchPage::ActionSwitcher::UpdateTopEditor( IEditorPart::Pointer newEditor) { if (topEditor.Lock() == newEditor) { return; } if (activePart == topEditor) { this->UpdateActivePart(newEditor); return; } QString oldId; if (!topEditor.Expired()) { oldId = topEditor.Lock()->GetSite()->GetId(); } QString newId; if (newEditor.IsNotNull()) { newId = newEditor->GetSite()->GetId(); } if (oldId == newId) { // we don't have to change anything topEditor = newEditor; return; } // Remove the contributions of the old editor if (!topEditor.Expired()) { this->DeactivateContributions(topEditor.Lock(), true); } // Show (disabled) the contributions of the new editor if (newEditor.IsNotNull()) { this->ActivateContributions(newEditor, false); } // ArrayList newActionSets = calculateActionSets(activePart, newEditor); // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } topEditor = newEditor; } void WorkbenchPage::ActionSwitcher::ActivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*enable*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->ActivateActionBars(enable); } void WorkbenchPage::ActionSwitcher::DeactivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*remove*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->DeactivateActionBars(remove); } IExtensionPoint::Pointer WorkbenchPage::GetPerspectiveExtensionPoint() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input) { if (layoutID == "") { throw WorkbenchException("Perspective ID is undefined"); } this->Register(); this->Init(w, layoutID, input, true); this->UnRegister(false); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, IAdaptable* input) { this->Register(); this->Init(w, "", input, false); this->UnRegister(false); } void WorkbenchPage::Activate(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } if (window->IsClosing()) { return; } // if (composite!=0 && composite.isVisible() && !((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // Activate part. //if (window.getActivePage() == this) { IWorkbenchPartReference::Pointer ref = this->GetReference(part); this->InternalBringToTop(ref); this->SetActivePart(part); } void WorkbenchPage::ActivatePart(const IWorkbenchPart::Pointer part) { // Platform.run(new SafeRunnable(WorkbenchMessages.WorkbenchPage_ErrorActivatingView) // { // public void WorkbenchPage::run() // { if (part.IsNotNull()) { //part.setFocus(); PartPane::Pointer pane = this->GetPane(part); pane->SetFocus(); PartSite::Pointer site = part->GetSite().Cast (); pane->ShowFocus(true); //this->UpdateTabList(part); //SubActionBars bars = (SubActionBars) site.getActionBars(); //bars.partChanged(part); } // } // } // ); } void WorkbenchPage::AddPartListener(IPartListener* l) { partList->GetPartService()->AddPartListener(l); } void WorkbenchPage::AddSelectionListener(ISelectionListener* listener) { selectionService->AddSelectionListener(listener); } void WorkbenchPage::AddSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddSelectionListener(partId, listener); } void WorkbenchPage::AddPostSelectionListener( ISelectionListener* listener) { selectionService->AddPostSelectionListener(listener); } void WorkbenchPage::AddPostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddPostSelectionListener(partId, listener); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPartReference::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPart::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return this->GetPane(this->GetReference(part)); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPartReference::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return part.Cast ()->GetPane(); } bool WorkbenchPage::InternalBringToTop(IWorkbenchPartReference::Pointer part) { bool broughtToTop = false; // Move part. if (part.Cast ().IsNotNull()) { ILayoutContainer::Pointer container = this->GetContainer(part); if (container.Cast () != 0) { PartStack::Pointer stack = container.Cast (); PartPane::Pointer newPart = this->GetPane(part); if (stack->GetSelection() != newPart) { stack->SetSelection(newPart); } broughtToTop = true; } } else if (part.Cast ().IsNotNull()) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { broughtToTop = persp->BringToTop(part.Cast ()); } } // Ensure that this part is considered the most recently activated part // in this stack activationList->BringToTop(part); return broughtToTop; } void WorkbenchPage::BringToTop(IWorkbenchPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return; } // if (!((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // QString label; // debugging only // if (UIStats.isDebugging(UIStats.BRING_PART_TO_TOP)) // { // label = part != 0 ? part.getTitle() : "none"; //$NON-NLS-1$ // } IWorkbenchPartReference::Pointer ref = this->GetReference(part); ILayoutContainer::Pointer activeEditorContainer = this->GetContainer( this->GetActiveEditor().Cast ()); ILayoutContainer::Pointer activePartContainer = this->GetContainer( this->GetActivePart()); ILayoutContainer::Pointer newPartContainer = this->GetContainer(part); if (newPartContainer == activePartContainer) { this->MakeActive(ref); } else if (newPartContainer == activeEditorContainer) { if (ref.Cast () != 0) { if (part != 0) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () != 0) { ref = site.Cast ()->GetPane()->GetPartReference(); } } this->MakeActiveEditor(ref.Cast ()); } else { this->MakeActiveEditor(IEditorReference::Pointer(0)); } } else { this->InternalBringToTop(ref); if (ref != 0) { partList->FirePartBroughtToTop(ref); } } } void WorkbenchPage::BusyResetPerspective() { ViewIntroAdapterPart::Pointer introViewAdapter = dynamic_cast (GetWorkbenchWindow() ->GetWorkbench()->GetIntroManager())->GetIntroAdapterPart().Cast< ViewIntroAdapterPart> (); // PartPane introPane = 0; // boolean introFullScreen = false; // if (introViewAdapter != 0) // { // introPane = ((PartSite) introViewAdapter.getSite()).getPane(); // introViewAdapter.setHandleZoomEvents(false); // introFullScreen = introPane.isZoomed(); // } // //try to prevent intro flicker. // if (introFullScreen) // { // window.getShell().setRedraw(false); // } // try // { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } // Get the current perspective. // This describes the working layout of the page and differs from // the original template. Perspective::Pointer oldPersp = this->GetActivePerspective(); // Map the current perspective to the original template. // If the original template cannot be found then it has been deleted. // In that case just return. (PR#1GDSABU). IPerspectiveRegistry* reg = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry(); PerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId( oldPersp->GetDesc()->GetId()).Cast (); if (desc == 0) { desc = reg->FindPerspectiveWithId(oldPersp ->GetDesc().Cast< PerspectiveDescriptor> ()->GetOriginalId()).Cast< PerspectiveDescriptor> (); } if (desc == 0) { return; } // Notify listeners that we are doing a reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET); // Create new persp from original template. // Suppress the perspectiveOpened and perspectiveClosed events otherwise it looks like two // instances of the same perspective are open temporarily (see bug 127470). Perspective::Pointer newPersp = this->CreatePerspective(desc, false); if (newPersp == 0) { // We're not going through with the reset, so it is complete. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); return; } // Update the perspective list and shortcut perspList.Swap(oldPersp, newPersp); // Install new persp. this->SetPerspective(newPersp); // Destroy old persp. this->DisposePerspective(oldPersp, false); // Update the Coolbar layout. this->ResetToolBarLayout(); // restore the maximized intro if (introViewAdapter) { try { // ensure that the intro is visible in the new perspective ShowView(IntroConstants::INTRO_VIEW_ID); // if (introFullScreen) // { // toggleZoom(introPane.getPartReference()); // } } catch (PartInitException& e) { //TODO IStatus WorkbenchPlugin::Log("Could not restore intro", e); // WorkbenchPlugin.getStatus(e)); } // finally // { // // we want the intro back to a normal state before we fire the event // introViewAdapter.setHandleZoomEvents(true); // } } // Notify listeners that we have completed our reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); // } // finally // { // // reset the handling of zoom events (possibly for the second time) in case there was // // an exception thrown // if (introViewAdapter != 0) // { // introViewAdapter.setHandleZoomEvents(true); // } // // if (introFullScreen) // { // window.getShell().setRedraw(true); // } // } } void WorkbenchPage::RemovePerspective(IPerspectiveDescriptor::Pointer desc) { Perspective::Pointer newPersp; PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(desc); perspList.Remove(newPersp); } void WorkbenchPage::BusySetPerspective(IPerspectiveDescriptor::Pointer desc) { // Create new layout. QString label = desc->GetId(); // debugging only Perspective::Pointer newPersp; //try //{ //UIStats.start(UIStats.SWITCH_PERSPECTIVE, label); PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(realDesc); if (newPersp == 0) { newPersp = this->CreatePerspective(realDesc, true); if (newPersp == 0) { return; } } // Change layout. this->SetPerspective(newPersp); // } // catch (std::exception& e) // { // UIStats.end(UIStats.SWITCH_PERSPECTIVE, desc.getId(), label); // throw e; // } } IViewPart::Pointer WorkbenchPage::BusyShowView(const QString& viewID, const QString& secondaryID, int mode) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewPart::Pointer(0); } // If this view is already visible just return. IViewReference::Pointer ref = persp->FindView(viewID, secondaryID); IViewPart::Pointer view; if (ref != 0) { view = ref->GetView(true); } if (view != 0) { this->BusyShowView(view, mode); return view; } // Show the view. view = persp->ShowView(viewID, secondaryID); if (view != 0) { this->BusyShowView(view, mode); IWorkbenchPartReference::Pointer partReference = this->GetReference(view); PartPane::Pointer partPane = this->GetPane(partReference); partPane->SetInLayout(true); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, GetPerspective(), partReference, CHANGE_VIEW_SHOW); window->FirePerspectiveChanged(thisPage, GetPerspective(), CHANGE_VIEW_SHOW); } return view; } void WorkbenchPage::BusyShowView(IViewPart::Pointer part, int mode) { // if (!((GrabFocus) Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } if (mode == VIEW_ACTIVATE) { this->Activate(part); } else if (mode == VIEW_VISIBLE) { IWorkbenchPartReference::Pointer ref = this->GetActivePartReference(); // if there is no active part or it's not a view, bring to top if (ref == 0 || ref.Cast () == 0) { this->BringToTop(part); } else { // otherwise check to see if the we're in the same stack as the active view IViewReference::Pointer activeView = ref.Cast (); QList viewStack = this->GetViewReferenceStack(part); for (int i = 0; i < viewStack.size(); i++) { if (viewStack[i] == activeView) { return; } } this->BringToTop(part); } } } bool WorkbenchPage::CertifyPart(IWorkbenchPart::Pointer part) { //Workaround for bug 22325 if (part != 0 && part->GetSite().Cast () == 0) { return false; } if (part.Cast () != 0) { IEditorReference::Pointer ref = this->GetReference(part).Cast< IEditorReference> (); return ref != 0 && this->GetEditorManager()->ContainsEditor(ref); } if (part.Cast () != 0) { Perspective::Pointer persp = this->GetActivePerspective(); return persp != 0 && persp->ContainsView(part.Cast ()); } return false; } bool WorkbenchPage::Close() { bool ret; //BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { ret = window->ClosePage(IWorkbenchPage::Pointer(this), true); // } // }); return ret; } bool WorkbenchPage::CloseAllSavedEditors() { // get the Saved editors QList editors = this->GetEditorReferences(); QList savedEditors; for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { IEditorReference::Pointer editor = *iter; if (!editor->IsDirty()) { savedEditors.push_back(editor); } } //there are no unsaved editors if (savedEditors.empty()) { return true; } return this->CloseEditors(savedEditors, false); } bool WorkbenchPage::CloseAllEditors(bool save) { return this->CloseEditors(this->GetEditorReferences(), save); } void WorkbenchPage::UpdateActivePart() { if (this->IsDeferred()) { return; } IWorkbenchPartReference::Pointer oldActivePart = partList->GetActivePartReference(); IWorkbenchPartReference::Pointer oldActiveEditor = partList->GetActiveEditorReference(); IWorkbenchPartReference::Pointer newActivePart; IEditorReference::Pointer newActiveEditor; if (!window->IsClosing()) { // If an editor is active, try to keep an editor active if (oldActiveEditor && oldActivePart == oldActiveEditor) { newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); newActivePart = newActiveEditor; if (newActivePart == 0) { // Only activate a non-editor if there's no editors left newActivePart = activationList->GetActiveReference(false); } } else { // If a non-editor is active, activate whatever was activated most recently newActivePart = activationList->GetActiveReference(false); if (newActivePart.Cast () != 0) { // If that happens to be an editor, make it the active editor as well newActiveEditor = newActivePart.Cast (); } else { // Otherwise, select whatever editor was most recently active newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); } } } if (oldActiveEditor != newActiveEditor) { this->MakeActiveEditor(newActiveEditor); } if (newActivePart != oldActivePart) { this->MakeActive(newActivePart); } } void WorkbenchPage::MakeActive(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { IWorkbenchPart::Pointer newActive = ref->GetPart(true); if (newActive == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { this->Activate(newActive); } } } void WorkbenchPage::MakeActiveEditor(IEditorReference::Pointer ref) { if (ref == this->GetActiveEditorReference()) { return; } IEditorPart::Pointer part = (ref == 0) ? IEditorPart::Pointer(0) : ref->GetEditor(true); if (part) { editorMgr->SetVisibleEditor(ref, false); //navigationHistory.MarkEditor(part); } actionSwitcher.UpdateTopEditor(part); if (ref) { activationList->BringToTop(this->GetReference(part)); } partList->SetActiveEditor(ref); } bool WorkbenchPage::CloseEditors( const QList& refArray, bool save) { if (refArray.empty()) { return true; } IWorkbenchPage::Pointer thisPage(this); // Check if we're being asked to close any parts that are already closed or cannot // be closed at this time QList editorRefs; for (QList::const_iterator iter = refArray.begin(); iter != refArray.end(); ++iter) { IEditorReference::Pointer reference = *iter; // If we're in the middle of creating this part, this is a programming error. Abort the entire // close operation. This usually occurs if someone tries to open a dialog in a method that // isn't allowed to do so, and a *syncExec tries to close the part. If this shows up in a log // file with a dialog's event loop on the stack, then the code that opened the dialog is usually // at fault. if (partBeingActivated == reference) { ctkRuntimeException re( "WARNING: Blocked recursive attempt to close part " + partBeingActivated->GetId() + " while still in the middle of activating it"); WorkbenchPlugin::Log(re); return false; } // if (reference.Cast () != 0) // { // WorkbenchPartReference::Pointer ref = reference.Cast(); // // // If we're being asked to close a part that is disposed (ie: already closed), // // skip it and proceed with closing the remaining parts. // if (ref.isDisposed()) // { // continue; // } // } editorRefs.push_back(reference); } // notify the model manager before the close QList partsToClose; for (int i = 0; i < editorRefs.size(); i++) { IWorkbenchPart::Pointer refPart = editorRefs[i]->GetPart(false); if (refPart != 0) { partsToClose.push_back(refPart); } } SaveablesList::Pointer modelManager; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (partsToClose.size() > 0) { modelManager = dynamic_cast( this->GetWorkbenchWindow()->GetService()); // this may prompt for saving and return 0 if the user canceled: postCloseInfo = modelManager->PreCloseParts(partsToClose, save, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { return false; } } // Fire pre-removal changes for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Notify interested listeners before the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_CLOSE); } this->DeferUpdates(true); try { if (modelManager != 0) { modelManager->PostClose(postCloseInfo); } // Close all editors. for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Remove editor from the presentation editorPresentation->CloseEditor(ref); this->PartRemoved(ref.Cast ()); } } catch (...) { } this->DeferUpdates(false); // Notify interested listeners after the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_CLOSE); // Return true on success. return true; } void WorkbenchPage::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferring(); } deferCount++; } else { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } void WorkbenchPage::StartDeferring() { //editorPresentation.getLayoutPart().deferUpdates(true); } void WorkbenchPage::HandleDeferredEvents() { editorPresentation->GetLayoutPart()->DeferUpdates(false); this->UpdateActivePart(); QList disposals = pendingDisposals; pendingDisposals.clear(); for (int i = 0; i < disposals.size(); i++) { this->DisposePart(disposals[i]); } } bool WorkbenchPage::IsDeferred() { return deferCount > 0; } bool WorkbenchPage::CloseEditor(IEditorReference::Pointer editorRef, bool save) { QList list; list.push_back(editorRef); return this->CloseEditors(list, save); } bool WorkbenchPage::CloseEditor(IEditorPart::Pointer editor, bool save) { IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast ().IsNotNull()) { QList list; list.push_back(ref.Cast ()); return this->CloseEditors(list, save); } return false; } void WorkbenchPage::CloseCurrentPerspective(bool saveParts, bool closePage) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) { Perspective::Pointer persp = this->FindPerspective(desc); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(Perspective::Pointer persp, bool saveParts, bool closePage) { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } QList partsToSave; QList viewsToClose; // collect views that will go away and views that are dirty QList viewReferences = persp->GetViewReferences(); for (int i = 0; i < viewReferences.size(); i++) { IViewReference::Pointer reference = viewReferences[i]; if (this->GetViewFactory()->GetReferenceCount(reference) == 1) { IViewPart::Pointer viewPart = reference->GetView(false); if (viewPart != 0) { viewsToClose.push_back(viewPart); if (saveParts && reference->IsDirty()) { partsToSave.push_back(viewPart); } } } } if (saveParts && perspList.Size() == 1) { // collect editors that are dirty QList editorReferences = this->GetEditorReferences(); for (QList::iterator refIter = editorReferences.begin(); refIter != editorReferences.end(); ++refIter) { IEditorReference::Pointer reference = *refIter; if (reference->IsDirty()) { IEditorPart::Pointer editorPart = reference->GetEditor(false); if (editorPart != 0) { partsToSave.push_back(editorPart); } } } } if (saveParts && !partsToSave.empty()) { if (!EditorManager::SaveAll(partsToSave, true, true, false, IWorkbenchWindow::Pointer(window))) { // user canceled return; } } // Close all editors on last perspective close if (perspList.Size() == 1 && this->GetEditorManager()->GetEditorCount() > 0) { // Close all editors if (!this->CloseAllEditors(false)) { return; } } // closeAllEditors already notified the saveables list about the editors. SaveablesList::Pointer saveablesList( dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); // we took care of the saving already, so pass in false (postCloseInfo will be non-0) SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(viewsToClose, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); // Dispose of the perspective bool isActive = (perspList.GetActive() == persp); if (isActive) { this->SetPerspective(perspList.GetNextActive()); } this->DisposePerspective(persp, true); if (closePage && perspList.Size() == 0) { this->Close(); } } void WorkbenchPage::CloseAllPerspectives(bool saveEditors, bool closePage) { if (perspList.IsEmpty()) { return; } // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } if (saveEditors) { if (!this->SaveAllEditors(true)) { return; } } // Close all editors if (!this->CloseAllEditors(false)) { return; } // Deactivate the active perspective and part this->SetPerspective(Perspective::Pointer(0)); // Close each perspective in turn PerspectiveList oldList = perspList; perspList = PerspectiveList(); for (PerspectiveList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { this->ClosePerspective(*itr, false, false); } if (closePage) { this->Close(); } } void WorkbenchPage::CreateClientComposite() { void* parent = window->GetPageComposite(); // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() // { composite = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateClientComposite( parent); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); // Make visible on activate. // force the client composite to be layed out // parent.layout(); // } // }); } Perspective::Pointer WorkbenchPage::CreatePerspective( PerspectiveDescriptor::Pointer desc, bool notify) { QString label = desc->GetId(); // debugging only try { //UIStats.start(UIStats.CREATE_PERSPECTIVE, label); WorkbenchPage::Pointer thisPage(this); Perspective::Pointer persp(new Perspective(desc, thisPage)); perspList.Add(persp); if (notify) { window->FirePerspectiveOpened(thisPage, desc); } //if the perspective is fresh and uncustomzied then it is not dirty //no reset will be prompted for if (!desc->HasCustomDefinition()) { dirtyPerspectives.erase(desc->GetId()); } return persp; } catch (WorkbenchException& /*e*/) { if (!window->GetWorkbenchImpl()->IsStarting()) { QMessageBox::critical(reinterpret_cast(window->GetShell()->GetControl()), "Error", "Problems opening perspective \"" + desc->GetId() + "\""); } return Perspective::Pointer(0); } // finally // { // UIStats.end(UIStats.CREATE_PERSPECTIVE, desc.getId(), label); // } } void WorkbenchPage::PartAdded(WorkbenchPartReference::Pointer ref) { activationList->Add(ref); partList->AddPart(ref); this->UpdateActivePart(); } void WorkbenchPage::PartRemoved(WorkbenchPartReference::Pointer ref) { activationList->Remove(ref); this->DisposePart(ref); } void WorkbenchPage::DisposePart(WorkbenchPartReference::Pointer ref) { if (this->IsDeferred()) { pendingDisposals.push_back(ref); } else { partList->RemovePart(ref); ref->Dispose(); } } void WorkbenchPage::DeactivatePart(IWorkbenchPart::Pointer part) { if (part.IsNotNull()) { PartSite::Pointer site = part->GetSite().Cast (); site->GetPane()->ShowFocus(false); } } void WorkbenchPage::DetachView(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } PerspectiveHelper* presentation = persp->GetPresentation(); presentation->DetachPart(ref); } void WorkbenchPage::AttachView(IViewReference::Pointer ref) { PerspectiveHelper* presentation = this->GetPerspectivePresentation(); presentation->AttachPart(ref); } WorkbenchPage::~WorkbenchPage() { // increment reference count to prevent recursive deletes this->Register(); { { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); // Close and dispose the editors. this->CloseAllEditors(false); // Need to make sure model data is cleaned up when the page is // disposed. Collect all the views on the page and notify the // saveable list of a pre/post close. This will free model data. QList partsToClose = this->GetOpenParts(); QList dirtyParts; for (int i = 0; i < partsToClose.size(); i++) { IWorkbenchPart::Pointer part = partsToClose[i]->GetPart(false); if (part != 0 && part.Cast () != 0) { dirtyParts.push_back(part); } } SaveablesList::Pointer saveablesList(dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(dirtyParts, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); IWorkbenchPage::Pointer thisPage(this); // Get rid of perspectives. This will close the views for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer perspective = *itr; window->FirePerspectiveClosed(thisPage, perspective->GetDesc()); //perspective->Dispose(); } perspList = PerspectiveList(); // Get rid of editor presentation. //editorPresentation->Dispose(); // Get rid of composite. //composite.dispose(); //navigationHistory.dispose(); //stickyViewMan.clear(); // if (tracker != 0) // { // tracker.close(); // } // // if we're destroying a window in a non-shutdown situation then we should // // clean up the working set we made. // if (!window->GetWorkbench()->IsClosing()) // { // if (aggregateWorkingSet != 0) // { // PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet( // aggregateWorkingSet); // } // } } partBeingActivated = 0; pendingDisposals.clear(); stickyViewMan = 0; delete viewFactory; delete editorPresentation; delete editorMgr; delete activationList; deferredActivePersp = 0; dirtyPerspectives.clear(); delete selectionService; partList.reset(); } // decrement reference count again, without explicit deletion this->UnRegister(false); } void WorkbenchPage::DisposePerspective(Perspective::Pointer persp, bool notify) { // Get rid of perspective. perspList.Remove(persp); if (notify) { IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveClosed(thisPage, persp->GetDesc()); } //persp->Dispose(); stickyViewMan->Remove(persp->GetDesc()->GetId()); } Perspective::Pointer WorkbenchPage::FindPerspective( IPerspectiveDescriptor::Pointer desc) { for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer mgr = *itr; if (desc->GetId() == mgr->GetDesc()->GetId()) { return mgr; } } return Perspective::Pointer(0); } IViewPart::Pointer WorkbenchPage::FindView(const QString& id) { IViewReference::Pointer ref = this->FindViewReference(id); if (ref == 0) { return IViewPart::Pointer(0); } return ref->GetView(true); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId) { return this->FindViewReference(viewId, ""); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId, const QString& secondaryId) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewReference::Pointer(0); } return persp->FindView(viewId, secondaryId); } IEditorPart::Pointer WorkbenchPage::GetActiveEditor() { return partList->GetActiveEditor(); } IEditorReference::Pointer WorkbenchPage::GetActiveEditorReference() { return partList->GetActiveEditorReference(); } IWorkbenchPart::Pointer WorkbenchPage::GetActivePart() { return partList->GetActivePart(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetActivePartReference() { return partList->GetActivePartReference(); } Perspective::Pointer WorkbenchPage::GetActivePerspective() { return perspList.GetActive(); } void* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } bool WorkbenchPage::HasView(const QString& perspectiveId, const QString& viewId) { PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives(); for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++) { SmartPointer p = *it; if (p->GetDesc()->GetId() == perspectiveId) { if (p->ContainsView(viewId)) { return true; } } } return false; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } QList WorkbenchPage::GetEditors() { QList refs = this->GetEditorReferences(); QList result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (QList::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } QList WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } QList WorkbenchPage::GetDirtyParts() { QList result; QList allParts = this->GetAllParts(); for (int i = 0; i < allParts.size(); i++) { IWorkbenchPartReference::Pointer reference = allParts[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0 && part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty()) { result.push_back(saveable); } } } return result; } IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input) { return this->GetEditorManager()->FindEditor(input); } QList WorkbenchPage::FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } QList WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } QString WorkbenchPage::GetLabel() { QString label = ""; // IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input, // IWorkbenchAdapter.class); // if (adapter != 0) // { // label = adapter.getLabel(input); // } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { label = label + " - " + persp->GetDesc()->GetLabel(); } else if (deferredActivePersp != 0) { label = label + " - " + deferredActivePersp->GetLabel(); } return label; } IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective() { if (deferredActivePersp != 0) { return deferredActivePersp; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetDesc(); } else { return IPerspectiveDescriptor::Pointer(0); } } ISelection::ConstPointer WorkbenchPage::GetSelection() const { return selectionService->GetSelection(); } ISelection::ConstPointer WorkbenchPage::GetSelection(const QString& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const QString& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } QList WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return QList(); } } QList WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } QList WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } QList parts; if (persp != 0) { QList refs = persp->GetViewReferences(); for (int i = 0; i < refs.size(); i++) { IViewPart::Pointer part = refs[i]->GetPart(restore).Cast (); if (part != 0) { parts.push_back(part); } } } return parts; } IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() { return IWorkbenchWindow::Pointer(window); } void WorkbenchPage::HideView(IViewReference::Pointer ref) { // Sanity check. if (ref == 0) { return; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } bool promptedForSave = false; IViewPart::Pointer view = ref->GetView(false); if (view != 0) { if (!this->CertifyPart(view)) { return; } // Confirm. if (view.Cast () != 0) { ISaveablePart::Pointer saveable = view.Cast (); if (saveable->IsSaveOnCloseNeeded()) { IWorkbenchWindow::Pointer window = view->GetSite()->GetWorkbenchWindow(); QList partsToSave; partsToSave.push_back(view); bool success = EditorManager::SaveAll(partsToSave, true, true, false, window); if (!success) { // the user cancelled. return; } promptedForSave = true; } } } int refCount = this->GetViewFactory()->GetReferenceCount(ref); SaveablesList* saveablesList = NULL; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = dynamic_cast( actualPart->GetSite()->GetService()); QList partsToClose; partsToClose.push_back(actualPart); postCloseInfo = saveablesList->PreCloseParts(partsToClose, !promptedForSave, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { // cancel return; } } } IWorkbenchPage::Pointer thisPage(this); // Notify interested listeners before the hide window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref, CHANGE_VIEW_HIDE); PartPane::Pointer pane = this->GetPane(ref.Cast ()); pane->SetInLayout(false); this->UpdateActivePart(); if (saveablesList != 0) { saveablesList->PostClose(postCloseInfo); } // Hide the part. persp->HideView(ref); // Notify interested listeners after the hide window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_VIEW_HIDE); } void WorkbenchPage::RefreshActiveView() { this->UpdateActivePart(); } void WorkbenchPage::HideView(IViewPart::Pointer view) { this->HideView(this->GetReference(view).Cast ()); } void WorkbenchPage::Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras) { // Save args. this->window = w; this->input = input; this->composite = 0; this->viewFactory = 0; this->activationList = new ActivationList(this); this->selectionService = new PageSelectionService(this); this->partList.reset(new WorkbenchPagePartList(this->selectionService)); this->stickyViewMan = new StickyViewManager(this); //actionSets = new ActionSetManager(w); deferCount = 0; // Create presentation. this->CreateClientComposite(); editorPresentation = new EditorAreaHelper(this); editorMgr = new EditorManager(WorkbenchWindow::Pointer(window), WorkbenchPage::Pointer(this), editorPresentation); //TODO WorkbenchPage perspective reorder listener? // // add this page as a client to be notified when the UI has re-ordered perspectives // // so that the order can be properly maintained in the receiver. // // E.g. a UI might support drag-and-drop and will need to make this known to ensure // // #saveState and #restoreState do not lose this re-ordering // w.addPerspectiveReorderListener(new IReorderListener() // { // public void WorkbenchPage::reorder(Object perspective, int newLoc) // { // perspList.reorder((IPerspectiveDescriptor)perspective, newLoc); // } // }); if (openExtras) { this->OpenPerspectiveExtras(); } // Get perspective descriptor. if (layoutID != "") { PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( layoutID).Cast (); if (desc == 0) { throw WorkbenchException("Unable to create Perspective " + layoutID + ". There is no corresponding perspective extension."); } Perspective::Pointer persp = this->FindPerspective(desc); if (persp == 0) { persp = this->CreatePerspective(desc, true); } perspList.SetActive(persp); window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc); } // getExtensionTracker() .registerHandler(perspectiveChangeHandler, // ExtensionTracker .createExtensionPointFilter( // getPerspectiveExtensionPoint())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras QString extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); QList descs; foreach (QString id, extras.split(", ", QString::SkipEmptyParts)) { if (id.trimmed().isEmpty()) continue; IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(id); if (desc != 0) { descs.push_back(desc); } } // HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list. // So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared. for (int i = (int) descs.size(); --i >= 0;) { PerspectiveDescriptor::Pointer desc = descs[i].Cast (); if (this->FindPerspective(desc) == 0) { this->CreatePerspective(desc, true); } } } bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); return pane != 0 && pane->GetVisible(); } bool WorkbenchPage::IsEditorAreaVisible() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return false; } return persp->IsEditorAreaVisible(); } bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { //return persp->IsFastView(ref); return false; } else { return false; } } bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsCloseable(ref); } return false; } bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsMoveable(ref); } return false; } bool WorkbenchPage::IsFixedLayout() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsFixedLayout(); } else { return false; } } bool WorkbenchPage::IsSaveNeeded() { return this->GetEditorManager()->IsSaveAllNeeded(); } void WorkbenchPage::OnActivate() { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true); Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->OnActivate(); this->UpdateVisibility(Perspective::Pointer(0), persp); } } void WorkbenchPage::OnDeactivate() { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); if (this->GetActivePerspective() != 0) { this->GetActivePerspective()->OnDeactivate(); } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); } void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) { // Rather than calling editor.setInput on the editor directly, we do it through the part reference. // This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response // to the input change... but if all editors obeyed their API contract, the "else" branch would be // sufficient. IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast () != 0) { EditorReference::Pointer editorRef = ref.Cast (); editorRef->SetInput(input); } else { editor->SetInput(input); } //navigationHistory.markEditor(editor); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { if (input == 0 || editorID == "") { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditor(input, editorID, activate, matchFlags, editorState); } IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor( IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { if (input == 0 || !(editorDescriptor.Cast () != 0)) { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast< EditorDescriptor> (), activate, editorState); // } // }); } IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor, activate, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched( IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { // If an editor already exists for the input, use it. IEditorPart::Pointer editor; // Reuse an existing open editor, unless we are in "new editor tab management" mode editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags); if (editor != 0) { if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID) { if (editor->IsDirty()) { QMessageBox::StandardButton saveFile = QMessageBox::question( this->GetWorkbenchWindow()->GetShell()->GetControl(), "Save", "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel); if (saveFile == QMessageBox::Yes) { // try // { IEditorPart::Pointer editorToSave = editor; // getWorkbenchWindow().run(false, false, // new IRunnableWithProgress() // { // public void WorkbenchPage::run(IProgressMonitor monitor) // throws InvocationTargetException, // InterruptedException // { //TODO progress monitor editorToSave->DoSave();//monitor); // } // }); // } // catch (InvocationTargetException& e) // { // throw(RuntimeException) e->GetTargetException(); // } // catch (InterruptedException& e) // { // return 0; // } } else if (saveFile == QMessageBox::Cancel) { return IEditorPart::Pointer(0); } } } else { // // do the IShowEditorInput notification before showing the editor // // to reduce flicker // if (editor.Cast () != 0) // { // ((IShowEditorInput) editor).showEditorInput(input); // } this->ShowEditor(activate, editor); return editor; } } // Otherwise, create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor( editorID, input, true, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { IEditorPart::Pointer editor; // Create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor, input, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } void WorkbenchPage::OpenEmptyTab() { IEditorPart::Pointer editor; EditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEmptyTab().Cast (); if (ref != 0) { editor = ref->GetEmptyEditor( dynamic_cast (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor( EditorRegistry::EMPTY_EDITOR_ID).Cast ()); } if (editor != 0) { this->SetEditorAreaVisible(true); this->Activate(editor); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } } void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor) { this->SetEditorAreaVisible(true); if (activate) { //zoomOutIfNecessary(editor); this->Activate(editor); } else { this->BringToTop(editor); } } bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor) { WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast< WorkbenchPartReference> (); return ref != 0 && ref->IsPinned(); } /** * Removes an IPartListener from the part service. */ void WorkbenchPage::RemovePartListener(IPartListener* l) { partList->GetPartService()->RemovePartListener(l); } /** * Implements IWorkbenchPage * * @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener) * @since 2.0 * @deprecated individual views should store a working set if needed and * register a property change listener directly with the * working set manager to receive notification when the view * working set is removed. */ // void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) { // propertyChangeListeners.remove(listener); // } void WorkbenchPage::RemoveSelectionListener(ISelectionListener* listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener(ISelectionListener* listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemovePostSelectionListener(partId, listener); } void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } // Real work. this->SetActivePart(part); } /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ void WorkbenchPage::ResetPerspective() { // Run op in busy cursor. // Use set redraw to eliminate the "flash" that can occur in the // coolbar as the perspective is reset. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // try // { // mgr.getControl2().setRedraw(false); // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusyResetPerspective(); // } // }); // }finally // { // mgr.getControl2().setRedraw(true); // } } bool WorkbenchPage::RestoreState(IMemento::Pointer memento, const IPerspectiveDescriptor::Pointer activeDescriptor) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { this->DeferUpdates(true); // }}); try { // Restore working set QString pageName; memento->GetString(WorkbenchConstants::TAG_LABEL, pageName); // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH)) // { // label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$ // } try { //UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$ // MultiStatus result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToRestorePerspective, // pageName), 0); bool result = true; // String workingSetName = memento .getString( // IWorkbenchConstants.TAG_WORKING_SET); // if (workingSetName != 0) // { // AbstractWorkingSetManager // workingSetManager = // (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager(); // setWorkingSet(workingSetManager.getWorkingSet(workingSetName)); // } // // IMemento workingSetMem = memento .getChild( // IWorkbenchConstants.TAG_WORKING_SETS); // if (workingSetMem != 0) // { // QList workingSetChildren = // workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET); // List workingSetList = new ArrayList(workingSetChildren.length); // for (int i = 0; i < workingSetChildren.length; i++) // { // IWorkingSet // set = // getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet( // workingSetChildren[i].getID()); // if (set != 0) // { // workingSetList.add(set); // } // } // // workingSets = (IWorkingSet[]) workingSetList .toArray( // new IWorkingSet[workingSetList.size()]); // } // // aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID); // // IWorkingSet setWithId = // window.getWorkbench().getWorkingSetManager().getWorkingSet( // aggregateWorkingSetId); // // // check to see if the set has already been made and assign it if it has // if (setWithId.Cast () != 0) // { // aggregateWorkingSet = (AggregateWorkingSet) setWithId; // } // Restore editor manager. IMemento::Pointer childMem = memento->GetChild( WorkbenchConstants::TAG_EDITORS); //result.merge(getEditorManager().restoreState(childMem)); result &= this->GetEditorManager()->RestoreState(childMem); childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS); if (childMem) { //result.merge(getViewFactory().restoreState(childMem)); result &= this->GetViewFactory()->RestoreState(childMem); } // Get persp block. childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES); QString activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); QString activePartSecondaryID; if (!activePartID.isEmpty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.isEmpty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } QString activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. QList perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; IPerspectiveDescriptor::Pointer validPersp; for (int i = 0; i < perspMems.size(); i++) { IMemento::Pointer current = perspMems[i]; // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { Perspective::Pointer persp(new Perspective( PerspectiveDescriptor::Pointer(0), WorkbenchPage::Pointer(this))); //result.merge(persp.restoreState(current)); result &= persp->RestoreState(current); IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc.IsNotNull()) { validPersp=desc; } else { IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->CreatePerspective("Hallo",validPersp); } if (desc == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); //berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry()->Add window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc); // } // }); } bool restoreActivePerspective = false; if (!activeDescriptor) { restoreActivePerspective = true; } else if (activePerspective && activePerspective->GetDesc() == activeDescriptor) { restoreActivePerspective = true; } else { restoreActivePerspective = false; activePerspective = this->CreatePerspective(activeDescriptor.Cast< PerspectiveDescriptor> (), true); if (activePerspective == 0) { // result .merge( // new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.Workbench_showPerspectiveError, // activeDescriptor.getId()), 0)); result &= false; } } perspList.SetActive(activePerspective); // Make sure we have a valid perspective to work with, // otherwise return. activePerspective = perspList.GetActive(); if (activePerspective == 0) { activePerspective = perspList.GetNextActive(); perspList.SetActive(activePerspective); } if (activePerspective && restoreActivePerspective) { //result.merge(activePerspective.restoreState()); result &= activePerspective->RestoreState(); } if (activePerspective) { Perspective::Pointer myPerspective = activePerspective; QString myActivePartId = activePartID; QString mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.isEmpty()) { IWorkbenchPartReference::Pointer ref = myPerspective->FindView( myActivePartId, mySecondaryId); if (ref) { activationList->SetActive(ref); } } // }}); } // childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY); // if (childMem) // { // navigationHistory.restoreState(childMem); // } // else if (GetActiveEditor()) // { // navigationHistory.markEditor(getActiveEditor()); // } // // restore sticky view state stickyViewMan->Restore(memento); // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); return result; } catch (...) { // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ throw ; } } catch (...) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); throw; } } bool WorkbenchPage::SaveAllEditors(bool confirm) { return this->SaveAllEditors(confirm, false); } bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources) { return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources); } bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm) { // Do not certify part do allow editors inside a multipageeditor to // call this. return this->GetEditorManager()->SavePart(saveable, part, confirm); } bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm) { return this->SavePart(editor, editor, confirm); } /** * Saves the current perspective. */ void WorkbenchPage::SavePerspective() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDesc(); } /** * Saves the perspective. */ void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc(); // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDescAs(newDesc); window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc); } /** * Save the state of the page. */ bool WorkbenchPage::SaveState(IMemento::Pointer memento) { // // We must unzoom to get correct layout. // if (isZoomed()) // { // zoomOut(); // } // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToSavePerspective, // getLabel()), 0); bool result = true; // Save editor manager. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS); //result.merge(editorMgr.saveState(childMem)); result &= editorMgr->SaveState(childMem); childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS); //result.merge(getViewFactory().saveState(childMem)); result &= this->GetViewFactory()->SaveState(childMem); // Create persp block. childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES); if (this->GetPerspective()) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, this->GetPerspective()->GetId()); } if (this->GetActivePart() != 0) { if (this->GetActivePart().Cast ()) { IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast(); if (ref) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, ViewFactory::GetKey(ref)); } } else { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, this->GetActivePart()->GetSite()->GetId()); } } // Save each perspective in opened order for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { IMemento::Pointer gChildMem = childMem->CreateChild( WorkbenchConstants::TAG_PERSPECTIVE); //result.merge(persp.saveState(gChildMem)); result &= (*itr)->SaveState(gChildMem); } // // Save working set if set // if (workingSet != 0) // { // memento.putString(IWorkbenchConstants.TAG_WORKING_SET, // workingSet .getName()); // } // // IMemento workingSetMem = memento .createChild( // IWorkbenchConstants.TAG_WORKING_SETS); // for (int i = 0; i < workingSets.length; i++) // { // workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET, // workingSets[i].getName()); // } // // if (aggregateWorkingSetId != 0) // { // memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId); // } // // navigationHistory.saveState(memento .createChild( // IWorkbenchConstants.TAG_NAVIGATION_HISTORY)); // // save the sticky activation state stickyViewMan->Save(memento); return result; } QString WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } QString WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { return "0"; //$NON-NLS-1$ } return ref->GetId(); } void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize it. if (this->GetActivePart() == newPart) { return; } if (partBeingActivated != 0) { if (partBeingActivated->GetPart(false) != newPart) { WorkbenchPlugin::Log(ctkRuntimeException( QString("WARNING: Prevented recursive attempt to activate part ") + this->GetId(newPart) + " while still in the middle of activating part " + this->GetId( partBeingActivated))); } return; } //No need to change the history if the active editor is becoming the // active part // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.ACTIVATE_PART)) // { // label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$ // } try { IWorkbenchPartReference::Pointer partref = this->GetReference(newPart); IWorkbenchPartReference::Pointer realPartRef; if (newPart != 0) { IWorkbenchPartSite::Pointer site = newPart->GetSite(); if (site.Cast () != 0) { realPartRef = site.Cast ()->GetPane()->GetPartReference(); } } partBeingActivated = realPartRef; //UIStats.start(UIStats.ACTIVATE_PART, label); // Notify perspective. It may deactivate fast view. Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->PartActivated(newPart); } // Deactivate old part IWorkbenchPart::Pointer oldPart = this->GetActivePart(); if (oldPart != 0) { this->DeactivatePart(oldPart); } // Set active part. if (newPart != 0) { activationList->SetActive(newPart); if (newPart.Cast () != 0) { this->MakeActiveEditor(realPartRef.Cast ()); } } this->ActivatePart(newPart); actionSwitcher.UpdateActivePart(newPart); partList->SetActivePart(partref); } catch (std::exception& e) { partBeingActivated = 0; // Object blame = newPart == 0 ? (Object) this : newPart; // UIStats.end(UIStats.ACTIVATE_PART, blame, label); throw e; } partBeingActivated = 0; } void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } if (showEditorArea == persp->IsEditorAreaVisible()) { return; } // // If parts change always update zoom. // if (isZoomed()) // { // zoomOut(); // } // Update editor area visibility. IWorkbenchPage::Pointer thisPage(this); if (showEditorArea) { persp->ShowEditorArea(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_SHOW); } else { persp->HideEditorArea(); this->UpdateActivePart(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_HIDE); } } /** * Sets the layout of the page. Assumes the new perspective is not 0. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp) { // Don't do anything if already active layout Perspective::Pointer oldPersp = this->GetActivePerspective(); if (oldPersp == newPersp) { return; } window->LargeUpdateStart(); std::exception exc; bool exceptionOccured = false; try { IWorkbenchPage::Pointer thisPage(this); if (oldPersp != 0) { // fire the pre-deactivate window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc()); } if (newPersp != 0) { bool status = newPersp->RestoreState(); if (!status) { QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; QMessageBox::critical(reinterpret_cast(this->GetWorkbenchWindow()->GetShell()->GetControl()), title, msg); } } // Deactivate the old layout if (oldPersp != 0) { oldPersp->OnDeactivate(); // Notify listeners of deactivation window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc()); } // Activate the new layout perspList.SetActive(newPersp); if (newPersp != 0) { newPersp->OnActivate(); // Notify listeners of activation window->FirePerspectiveActivated(thisPage, newPersp->GetDesc()); } this->UpdateVisibility(oldPersp, newPersp); // Update the window //TODO action sets //window->UpdateActionSets(); // Update sticky views stickyViewMan->Update(oldPersp, newPersp); } catch (std::exception& e) { exc = e; exceptionOccured = true; } window->LargeUpdateEnd(); if (newPersp == 0) { return; } IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc(); if (desc == 0) { return; } if (dirtyPerspectives.erase(desc->GetId())) { this->SuggestReset(); } if (exceptionOccured) throw exc; } void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp, Perspective::Pointer newPersp) { // Flag all parts in the old perspective QList oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (int i = 0; i < oldRefs.size(); i++) { PartPane::Pointer pane = oldRefs[i].Cast ()->GetPane(); pane->SetInLayout(false); } } PerspectiveHelper* pres = 0; // Make parts in the new perspective visible if (newPersp != 0) { pres = newPersp->GetPresentation(); QList newRefs = newPersp->GetViewReferences(); for (int i = 0; i < newRefs.size(); i++) { WorkbenchPartReference::Pointer ref = newRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres->IsPartVisible(ref)) { activationList->BringToTop(ref); } pane->SetInLayout(true); } } this->UpdateActivePart(); // Hide any parts in the old perspective that are no longer visible for (int i = 0; i < oldRefs.size(); i++) { WorkbenchPartReference::Pointer ref = oldRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres == 0 || !pres->IsPartVisible(ref)) { pane->SetVisible(false); } } } /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc) { if (this->GetPerspective() == desc) { return; } // // Going from multiple to single rows can make the coolbar // // and its adjacent views appear jumpy as perspectives are // // switched. Turn off redraw to help with this. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); std::exception exc; bool exceptionOccured = false; try { //mgr.getControl2().setRedraw(false); //getClientComposite().setRedraw(false); // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusySetPerspective(desc); // } // }); } catch (std::exception& e) { exc = e; exceptionOccured = true; } // getClientComposite().setRedraw(true); // mgr.getControl2().setRedraw(true); IWorkbenchPart::Pointer part = this->GetActivePart(); if (part != 0) { part->SetFocus(); } if (exceptionOccured) throw exc; } PartService* WorkbenchPage::GetPartService() { return dynamic_cast (partList->GetPartService()); } void WorkbenchPage::ResetToolBarLayout() { // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // mgr.resetItemOrder(); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID, const QString& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.indexOf(ViewFactory::ID_SEP) != -1) { throw ctkInvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw ctkInvalidArgumentException("Illegal view mode"); } // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { // try // { return this->BusyShowView(viewID, secondaryID, mode); // } catch (PartInitException& e) // { // result = e; // } // } // }); } bool WorkbenchPage::CertifyMode(int mode) { if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE) return true; return false; } QList WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } QList WorkbenchPage::GetOpenPerspectives() { QList opened = perspList.GetOpenedPerspectives(); QList result; for (QList::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { QListIterator iter(perspList.GetSortedPerspectives()); iter.toBack(); while(iter.hasPrevious()) { Perspective::Pointer p = iter.previous(); if (p->ContainsView(part)) { return p; } }; // we should never get here return Perspective::Pointer(0); } QList WorkbenchPage::GetSortedPerspectives() { QList sortedArray = perspList.GetSortedPerspectives(); QList result; for (QList::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetSortedParts() { //return partList->GetParts(this->GetViewReferences()); return activationList->GetParts(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetReference( IWorkbenchPart::Pointer part) { if (part == 0) { return IWorkbenchPartReference::Pointer(0); } IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } PartSite::Pointer partSite = site.Cast (); PartPane::Pointer pane = partSite->GetPane(); return partSite->GetPartReference(); } // for dynamic UI void WorkbenchPage::AddPerspective(Perspective::Pointer persp) { perspList.Add(persp); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveOpened(thisPage, persp->GetDesc()); } QList WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return QList(); } ILayoutContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); QList list; ILayoutContainer::ChildrenType children = folder->GetChildren(); for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer stackablePart = *childIter; if (stackablePart.Cast () != 0) { IViewReference::Pointer view = stackablePart.Cast ()->GetPartReference().Cast< IViewReference> (); if (view != 0) { list.push_back(view); } } } // sort the list by activation order (most recently activated first) std::sort(list.begin(), list.end(), ActivationOrderPred(activationList)); return list; } QList result; result.push_back(this->GetReference(part).Cast ()); return result; } QList WorkbenchPage::GetViewStack( IViewPart::Pointer part) { QList refStack = this->GetViewReferenceStack( part); QList result; for (int i = 0; i < refStack.size(); i++) { IViewPart::Pointer next = refStack[i]->GetView(false); if (next != 0) { result.push_back(next); } } return result; } void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height) { SashInfo sashInfo; PartPane::Pointer pane = part->GetSite().Cast ()->GetPane(); ILayoutContainer::Pointer container = pane->GetContainer(); LayoutTree::Pointer tree = this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find( container.Cast ()); // retrieve our layout sashes from the layout tree this->FindSashParts(tree, pane->FindSashes(), sashInfo); // first set the width int deltaWidth = width - pane->GetBounds().width; if (sashInfo.right != 0) { Rectangle rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x) - rightBounds.x) / rightBounds.width); // complete the resize sashInfo.rightNode->SetBounds(rightBounds); } else if (sashInfo.left != 0) { Rectangle leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x - deltaWidth) - leftBounds.x) / leftBounds.width); // complete the resize sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds()); } // next set the height int deltaHeight = height - pane->GetBounds().height; if (sashInfo.bottom != 0) { Rectangle bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y) - bottomBounds.y) / bottomBounds.height); // complete the resize sashInfo.bottomNode->SetBounds(bottomBounds); } else if (sashInfo.top != 0) { Rectangle topBounds = sashInfo.topNode->GetBounds(); // set the ratio sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y - deltaHeight) - topBounds.y) / topBounds.height); // complete the resize sashInfo.topNode->SetBounds(topBounds); } } void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree, const PartPane::Sashes& sashes, SashInfo& info) { LayoutTree::Pointer parent(tree->GetParent()); if (parent == 0) { return; } if (parent->part.Cast () != 0) { // get the layout part sash from this tree node LayoutPartSash::Pointer sash = parent->part.Cast (); // make sure it has a sash control void* control = sash->GetControl(); if (control != 0) { // check for a vertical sash if (sash->IsVertical()) { if (sashes.left == control) { info.left = sash; info.leftNode = parent->FindSash(sash); } else if (sashes.right == control) { info.right = sash; info.rightNode = parent->FindSash(sash); } } // check for a horizontal sash else { if (sashes.top == control) { info.top = sash; info.topNode = parent->FindSash(sash); } else if (sashes.bottom == control) { info.bottom = sash; info.bottomNode = parent->FindSash(sash); } } } } // recursive call to continue up the tree this->FindSashParts(parent, sashes, info); } QList WorkbenchPage::GetAllParts() { QList views = viewFactory->GetViews(); QList editors = this->GetEditorReferences(); QList result; for (int i = 0; i < views.size(); i++) { result.push_back(views[i]); } for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { result.push_back(*iter); } return result; } QList WorkbenchPage::GetOpenParts() { QList refs = this->GetAllParts(); QList result; for (int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0) { result.push_back(reference); } } return result; } void WorkbenchPage::TestInvariants() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->TestInvariants(); // When we have widgets, ensure that there is no situation where the editor area is visible // and the perspective doesn't want an editor area. if (this->GetClientComposite() && editorPresentation->GetLayoutPart()->IsVisible()) { poco_assert(persp->IsEditorAreaVisible()); } } } /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() */ // IExtensionTracker WorkbenchPage::GetExtensionTracker() // { // if (tracker == 0) // { // tracker = new UIExtensionTracker(getWorkbenchWindow().getWorkbench().getDisplay()); // } // return tracker; // } /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ QList WorkbenchPage::GetPerspectiveShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetPerspectiveShortcuts(); } QList WorkbenchPage::GetShowViewShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetShowViewShortcuts(); } void WorkbenchPage::SuggestReset() { IWorkbench* workbench = this->GetWorkbenchWindow()->GetWorkbench(); // workbench.getDisplay().asyncExec(new Runnable() // { // public void WorkbenchPage::run() // { Shell::Pointer parentShell; IWorkbenchWindow::Pointer window = workbench->GetActiveWorkbenchWindow(); if (window == 0) { if (workbench->GetWorkbenchWindowCount() == 0) { return; } window = workbench->GetWorkbenchWindows()[0]; } parentShell = window->GetShell(); if (QMessageBox::question(parentShell.IsNull() ? NULL : reinterpret_cast(parentShell->GetControl()), "Reset Perspective?", "Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?") == QMessageBox::Yes) { IWorkbenchPage::Pointer page = window->GetActivePage(); if (page == 0) { return; } page->ResetPerspective(); } // } // }); } bool WorkbenchPage::IsPartVisible( IWorkbenchPartReference::Pointer reference) { IWorkbenchPart::Pointer part = reference->GetPart(false); // Can't be visible if it isn't created yet if (part == 0) { return false; } return this->IsPartVisible(part); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.cpp index 8f43e35166..f372feb8bc 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.cpp @@ -1,97 +1,96 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchPagePartList.h" #include "berryPartPane.h" -#include "berryImageDescriptor.h" namespace berry { void WorkbenchPagePartList::FirePartOpened(IWorkbenchPartReference::Pointer part) { partService.FirePartOpened(part); } void WorkbenchPagePartList::FirePartClosed(IWorkbenchPartReference::Pointer part) { partService.FirePartClosed(part); } void WorkbenchPagePartList::FirePartAdded(IWorkbenchPartReference::Pointer /*part*/) { // TODO: There is no listener for workbench page additions yet } void WorkbenchPagePartList::FirePartRemoved( IWorkbenchPartReference::Pointer /*part*/) { // TODO: There is no listener for workbench page removals yet } void WorkbenchPagePartList::FireActiveEditorChanged( IWorkbenchPartReference::Pointer ref) { if (ref.IsNotNull()) { this->FirePartBroughtToTop(ref); } } void WorkbenchPagePartList::FireActivePartChanged( IWorkbenchPartReference::Pointer /*oldRef*/, IWorkbenchPartReference::Pointer newRef) { partService.SetActivePart(newRef); IWorkbenchPart::Pointer realPart = newRef == 0 ? IWorkbenchPart::Pointer(0) : newRef->GetPart(false); selectionService->SetActivePart(realPart); } void WorkbenchPagePartList::FirePartHidden(IWorkbenchPartReference::Pointer ref) { partService.FirePartHidden(ref); } void WorkbenchPagePartList::FirePartVisible(IWorkbenchPartReference::Pointer ref) { partService.FirePartVisible(ref); } void WorkbenchPagePartList::FirePartInputChanged( IWorkbenchPartReference::Pointer ref) { partService.FirePartInputChanged(ref); } WorkbenchPagePartList::WorkbenchPagePartList(PageSelectionService* selService) : selectionService(selService), partService("", "") { } IPartService* WorkbenchPagePartList::GetPartService() { return &partService; } void WorkbenchPagePartList::FirePartBroughtToTop( IWorkbenchPartReference::Pointer ref) { partService.FirePartBroughtToTop(ref); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.cpp index 49549508ca..a3ec664dc0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.cpp @@ -1,717 +1,675 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchPartReference.h" #include #include #include "berryWorkbenchPlugin.h" #include "berryUtil.h" #include "berryPartPane.h" #include "berryIWorkbenchPartSite.h" #include "berryIEditorPart.h" #include "berryIWorkbenchPartConstants.h" -#include "berryImageDescriptor.h" + +#include namespace berry { int WorkbenchPartReference::STATE_LAZY = 0; int WorkbenchPartReference::STATE_CREATION_IN_PROGRESS = 1; int WorkbenchPartReference::STATE_CREATED = 2; int WorkbenchPartReference::STATE_DISPOSED = 3; WorkbenchPartReference::PropertyChangeListener::PropertyChangeListener( WorkbenchPartReference* ref) : partRef(ref) { } void WorkbenchPartReference::PropertyChangeListener::PropertyChange( const PropertyChangeEvent::Pointer& event) { if (event->GetProperty() == IWorkbenchPartConstants::INTEGER_PROPERTY) { partRef->PropertyChanged(event->GetSource(), event->GetNewValue().Cast()->GetValue()); } else { partRef->PropertyChanged(event); } } WorkbenchPartReference::WorkbenchPartReference() : state(STATE_LAZY) , pinned(false) - , image(0) , propertyChangeListener(new PropertyChangeListener(this)) { } WorkbenchPartReference::~WorkbenchPartReference() { this->Register(); part = 0; pane = 0; this->UnRegister(false); } bool WorkbenchPartReference::IsDisposed() const { return state == STATE_DISPOSED; } void WorkbenchPartReference::CheckReference() { if (state == STATE_DISPOSED) { throw Poco::RuntimeException("Error: IWorkbenchPartReference disposed"); //$NON-NLS-1$ } } /** * Calling this with deferEvents(true) will queue all property change events until a subsequent * call to deferEvents(false). This should be used at the beginning of a batch of related changes * to prevent duplicate property change events from being sent. * * @param shouldQueue */ //void WorkbenchPartReference::DeferEvents(bool shouldQueue) { // queueEvents = shouldQueue; // // if (queueEvents == false) { // // do not use nextSetBit, to allow compilation against JCL Foundation (bug 80053) // for (int i = 0, n = queuedEvents.size(); i < n; ++i) { // if (queuedEvents.get(i)) { // firePropertyChange(i); // queuedEvents.clear(i); // } // } // } // } void WorkbenchPartReference::SetPartName(const QString& newPartName) { if (partName == newPartName) { return; } partName = newPartName; this->FirePropertyChange(IWorkbenchPartConstants::PROP_PART_NAME); } void WorkbenchPartReference::SetContentDescription( const QString& newContentDescription) { if (contentDescription == newContentDescription) { return; } contentDescription = newContentDescription; this->FirePropertyChange(IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION); } void WorkbenchPartReference::SetImageDescriptor( - ImageDescriptor::Pointer descriptor) + const QIcon& descriptor) { - if (imageDescriptor == descriptor) + if (imageDescriptor.cacheKey() == descriptor.cacheKey()) { return; } - void* oldImage = image; - ImageDescriptor::Pointer oldDescriptor = imageDescriptor; - image = 0; imageDescriptor = descriptor; // Don't queue events triggered by image changes. We'll dispose the image // immediately after firing the event, so we need to fire it right away. this->ImmediateFirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); if (queueEvents) { // If there's a PROP_TITLE event queued, remove it from the queue because // we've just fired it. queuedEvents.remove(IWorkbenchPartConstants::PROP_TITLE); } - - // If we had allocated the old image, deallocate it now (AFTER we fire the property change - // -- listeners may need to clean up references to the old image) - if (oldImage && oldDescriptor) - { - //JFaceResources.getResources().destroy(oldDescriptor); - oldDescriptor->DestroyImage(oldImage); - } } void WorkbenchPartReference::SetToolTip(const QString& newToolTip) { if (tooltip == newToolTip) { return; } tooltip = newToolTip; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void WorkbenchPartReference::PropertyChanged(const Object::Pointer& /*source*/, int propId) { // We handle these properties directly (some of them may be transformed // before firing events to workbench listeners) if (propId == IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION || propId == IWorkbenchPartConstants::PROP_PART_NAME || propId == IWorkbenchPartConstants::PROP_TITLE) { this->RefreshFromPart(); } else { // Any other properties are just reported to listeners verbatim this->FirePropertyChange(propId); } // Let the model manager know as well // if (propId == IWorkbenchPartConstants::PROP_DIRTY) { // IWorkbenchPart actualPart = getPart(false); // if (actualPart != null) { // SaveablesList modelManager = (SaveablesList) actualPart.getSite().getService(ISaveablesLifecycleListener.class); // modelManager.dirtyChanged(actualPart); // } // } } void WorkbenchPartReference::PropertyChanged(const PropertyChangeEvent::Pointer& event) { this->FirePropertyChange(event); } /** * Refreshes all cached values with the values from the real part */ void WorkbenchPartReference::RefreshFromPart() { this->DeferEvents(true); SetPartName(ComputePartName()); SetContentDescription(ComputeContentDescription()); SetToolTip(GetRawToolTip()); //SetImageDescriptor(ComputeImageDescriptor()); this->DeferEvents(false); } -ImageDescriptor::Pointer WorkbenchPartReference::ComputeImageDescriptor() +QIcon WorkbenchPartReference::ComputeImageDescriptor() { if (part) { - return ImageDescriptor::CreateFromImage(part->GetTitleImage()); + return part->GetTitleImage(); } return defaultImageDescriptor; } void WorkbenchPartReference::Init(const QString& id, - const QString& tooltip, ImageDescriptor::Pointer desc, + const QString& tooltip, const QIcon& desc, const QString& paneName, const QString& contentDescription) { this->id = id; this->tooltip = tooltip; this->partName = paneName; this->contentDescription = contentDescription; this->defaultImageDescriptor = desc; this->imageDescriptor = this->ComputeImageDescriptor(); } /** * @see IWorkbenchPart */ void WorkbenchPartReference::AddPropertyListener(IPropertyChangeListener *listener) { propChangeEvents.AddListener(listener); } /** * @see IWorkbenchPart */ void WorkbenchPartReference::RemovePropertyListener(IPropertyChangeListener *listener) { propChangeEvents.RemoveListener(listener); } QString WorkbenchPartReference::GetId() const { if (!part.IsNull()) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (!site.IsNull()) { return site->GetId(); } } return id; } QString WorkbenchPartReference::GetTitleToolTip() const { return tooltip; } QString WorkbenchPartReference::GetRawToolTip() const { return part->GetTitleToolTip(); } /** * Returns the pane name for the part * * @return the pane name for the part */ QString WorkbenchPartReference::GetPartName() const { return partName; } /** * Gets the part name directly from the associated workbench part, * or the empty string if none. * * @return */ QString WorkbenchPartReference::GetRawPartName() const { return part->GetPartName(); } QString WorkbenchPartReference::ComputePartName() const { return this->GetRawPartName(); } /** * Returns the content description for this part. * * @return the pane name for the part */ QString WorkbenchPartReference::GetContentDescription() const { return contentDescription; } /** * Computes a new content description for the part. Subclasses may override to change the * default behavior * * @return the new content description for the part */ QString WorkbenchPartReference::ComputeContentDescription() const { return this->GetRawContentDescription(); } /** * Returns the content description as set directly by the part, or the empty string if none * * @return the unmodified content description from the part (or the empty string if none) */ QString WorkbenchPartReference::GetRawContentDescription() const { return part->GetContentDescription(); } bool WorkbenchPartReference::IsDirty() const { if (part.Cast ().IsNull()) { return false; } return part.Cast ()->IsDirty(); } -void* WorkbenchPartReference::GetTitleImage() -{ - if (this->IsDisposed()) - { - //return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW); - return 0; - } - - if (!image && imageDescriptor) - { - //image = JFaceResources.getResources().createImageWithDefault(imageDescriptor); - image = imageDescriptor->CreateImage(); - } - return image; -} - -ImageDescriptor::Pointer WorkbenchPartReference::GetTitleImageDescriptor() const +QIcon WorkbenchPartReference::GetTitleImage() const { - if (this->IsDisposed()) - { - //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); - return ImageDescriptor::Pointer(0); - } - return imageDescriptor; } void WorkbenchPartReference::FireVisibilityChange() { this->FirePropertyChange(IWorkbenchPartConstants::PROP_VISIBLE); } // /* package */ void fireZoomChange() { // fireInternalPropertyChange(INTERNAL_PROPERTY_ZOOMED); // } bool WorkbenchPartReference::GetVisible() { if (this->IsDisposed()) { return false; } return this->GetPane()->GetVisible(); } void WorkbenchPartReference::SetVisible(bool isVisible) { if (this->IsDisposed()) { return; } this->GetPane()->SetVisible(isVisible); } void WorkbenchPartReference::DeferEvents(bool shouldQueue) { queueEvents = shouldQueue; if (queueEvents == false) { QSet::iterator iter = queuedEvents.begin(); while (iter != queuedEvents.end()) { this->FirePropertyChange(*iter); queuedEvents.erase(iter++); } } } void WorkbenchPartReference::FirePropertyChange(int id) { if (queueEvents) { queuedEvents.insert(id); return; } this->ImmediateFirePropertyChange(id); } void WorkbenchPartReference::ImmediateFirePropertyChange(int id) { //UIListenerLogging.logPartReferencePropertyChange(this, id); ObjectInt::Pointer value(new ObjectInt(id)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, value, value)); propChangeEvents.propertyChange(event); } IWorkbenchPart::Pointer WorkbenchPartReference::GetPart(bool restore) { if (this->IsDisposed()) { return IWorkbenchPart::Pointer(0); } if (part.IsNull() && restore) { if (state == STATE_CREATION_IN_PROGRESS) { // IStatus result = WorkbenchPlugin.getStatus( // new PartInitException(NLS.bind("Warning: Detected recursive attempt by part {0} to create itself (this is probably, but not necessarily, a bug)", //$NON-NLS-1$ // getId()))); WorkbenchPlugin::Log("Warning: Detected recursive attempt by part " + GetId() + " to create itself (this is probably, but not necessarily, a bug)"); return IWorkbenchPart::Pointer(0); } try { state = STATE_CREATION_IN_PROGRESS; IWorkbenchPart::Pointer newPart = this->CreatePart(); if (!newPart.IsNull()) { part = newPart; // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. //this->GetPane().getControl().addDisposeListener(prematureDisposeListener); part->AddPropertyListener(propertyChangeListener.data()); this->RefreshFromPart(); this->FirePropertyChange(IWorkbenchPartConstants::PROP_OPENED); //ISizeProvider sizeProvider = (ISizeProvider) Util.getAdapter(part, ISizeProvider.class); //if (sizeProvider != null) { // If this part has a preferred size, indicate that the preferred size may have changed at this point if (this->GetSizeFlags(true) != 0 || this->GetSizeFlags(false) != 0) { this->FirePropertyChange(IWorkbenchPartConstants::PROP_PREFERRED_SIZE); } //} } state = STATE_CREATED; } catch (Poco::Exception& e) { state = STATE_CREATED; std::cerr << e.displayText() << std::flush; throw e; } catch (std::exception& e) { state = STATE_CREATED; throw e; } } return part; } /** * Returns the part pane for this part reference. Does not return null. Should not be called * if the reference has been disposed. * * TODO: clean up all code that has any possibility of calling this on a disposed reference * and make this method throw an exception if anyone else attempts to do so. * * @return */ PartPane::Pointer WorkbenchPartReference::GetPane() { // Note: we should never call this if the reference has already been disposed, since it // may cause a PartPane to be created and leaked. if (pane.IsNull()) { pane = this->CreatePane(); } return pane; } void WorkbenchPartReference::Dispose() { if (this->IsDisposed()) { return; } // Store the current title, tooltip, etc. so that anyone that they can be returned to // anyone that held on to the disposed reference. partName = GetPartName(); contentDescription = GetContentDescription(); tooltip = GetTitleToolTip(); if (state == STATE_CREATION_IN_PROGRESS) { // IStatus result = WorkbenchPlugin.getStatus( // new PartInitException(NLS.bind("Warning: Blocked recursive attempt by part {0} to dispose itself during creation", //$NON-NLS-1$ // getId()))); WorkbenchPlugin::Log("Warning: Blocked recursive attempt by part" + GetId() + " to dispose itself during creation"); return; } // Disposing the pane disposes the part's widgets. The part's widgets need to be disposed before the part itself. // if (pane != 0) { // // Remove the dispose listener since this is the correct place for the widgets to get disposed // Control targetControl = getPane().getControl(); // if (targetControl != null) { // targetControl.removeDisposeListener(prematureDisposeListener); // } // pane->Dispose(); // } this->DoDisposePart(); if (!pane.IsNull()) { //pane.removeContributions(); } //clearListenerList(internalPropChangeListeners); //clearListenerList(partChangeListeners); - void* oldImage = image; - ImageDescriptor::Pointer oldDescriptor = imageDescriptor; - image = 0; state = STATE_DISPOSED; - imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); - defaultImageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); + imageDescriptor = AbstractUICTKPlugin::GetMissingIcon(); + defaultImageDescriptor = imageDescriptor; this->ImmediateFirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); //clearListenerList(propChangeListeners); - if (oldImage) - { - //JFaceResources.getResources().destroy(oldDescriptor); - oldDescriptor->DestroyImage(oldImage); - } - pane = 0; } void WorkbenchPartReference::DoDisposePart() { if (part) { //this->FireInternalPropertyChange(INTERNAL_PROPERTY_CLOSED); this->FirePropertyChange(IWorkbenchPartConstants::PROP_CLOSED); // Don't let exceptions in client code bring us down. Log them and continue. try { part->RemovePropertyListener(propertyChangeListener.data()); // if (part instanceof IWorkbenchPart3) // { // ((IWorkbenchPart3) part).removePartPropertyListener( // partPropertyChangeListener); // } // part->Dispose(); part = 0; } catch (const ctkRuntimeException& e) { WorkbenchPlugin::Log(e); } catch (const std::exception& e) { QString msg("Exception in WorkbenchPartReference::DoDisposePart: "); msg.append(e.what()); WorkbenchPlugin::Log(msg); } part = 0; } } /** * Clears all of the listeners in a listener list. TODO Bug 117519 Remove * this method when fixed. * * @param list * The list to be clear; must not be null. */ //private: void clearListenerList(const ListenerList list) { // final Object[] listeners = list.getListeners(); // for (int i = 0; i < listeners.length; i++) { // list.remove(listeners[i]); // } // } void WorkbenchPartReference::SetPinned(bool newPinned) { if (IsDisposed()) { return; } if (newPinned == pinned) { return; } pinned = newPinned; //SetImageDescriptor(computeImageDescriptor()); this->FirePropertyChange(IWorkbenchPartConstants::PROP_PINNED); } bool WorkbenchPartReference::IsPinned() const { return pinned; } QString WorkbenchPartReference::GetPartProperty(const QString& key) const { if (part != 0) { return part->GetPartProperty(key); } else { QHash::const_iterator itr = propertyCache.find(key); if (itr == propertyCache.end()) return QString(); return itr.value(); } } void WorkbenchPartReference::FirePropertyChange( const PropertyChangeEvent::Pointer& event) { propChangeEvents.propertyChange(event); } void WorkbenchPartReference::CreatePartProperties( IWorkbenchPart::Pointer workbenchPart) { for (QHash::iterator iter = propertyCache.begin(); iter != propertyCache.end(); ++iter) { workbenchPart->SetPartProperty(iter.key(), iter.value()); } } int WorkbenchPartReference::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult) { ISizeProvider* sizeProvider = Util::GetAdapter(part); if (sizeProvider) { return sizeProvider->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredResult); } return preferredResult; } int WorkbenchPartReference::GetSizeFlags(bool width) { ISizeProvider* sizeProvider = Util::GetAdapter(part); if (sizeProvider) { return sizeProvider->GetSizeFlags(width); } return 0; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.h index 354a200757..f78f71bae6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPartReference.h @@ -1,304 +1,288 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHPARTREFERENCE_H_ #define BERRYWORKBENCHPARTREFERENCE_H_ #include #include "berryISizeProvider.h" #include "berryIWorkbenchPartReference.h" #include "berryIWorkbenchPart.h" -#include "berryImageDescriptor.h" +#include namespace berry { class PartPane; /** * \ingroup org_blueberry_ui_internal * */ class BERRY_UI_QT WorkbenchPartReference : virtual public IWorkbenchPartReference, public ISizeProvider { public: berryObjectMacro(WorkbenchPartReference) // State constants ////////////////////////////// - /** - * State constant indicating that the part is not created yet - */ -public: static int STATE_LAZY; // = 0 + /** + * State constant indicating that the part is not created yet + */ + static int STATE_LAZY; // = 0 - /** - * State constant indicating that the part is in the process of being created - */ -public: static int STATE_CREATION_IN_PROGRESS; // = 1 + /** + * State constant indicating that the part is in the process of being created + */ + static int STATE_CREATION_IN_PROGRESS; // = 1 - /** - * State constant indicating that the part has been created - */ -public: static int STATE_CREATED; // = 2 + /** + * State constant indicating that the part has been created + */ + static int STATE_CREATED; // = 2 - /** - * State constant indicating that the reference has been disposed (the reference shouldn't be - * used anymore) - */ -public: static int STATE_DISPOSED; // = 3 + /** + * State constant indicating that the reference has been disposed (the reference shouldn't be + * used anymore) + */ + static int STATE_DISPOSED; // = 3 - /** - * Current state of the reference. Used to detect recursive creation errors, disposed - * references, etc. - */ -private: int state; + WorkbenchPartReference(); + ~WorkbenchPartReference(); -protected: IWorkbenchPart::Pointer part; + virtual bool IsDisposed() const; -protected: SmartPointer pane; + virtual void Init(const QString& id, const QString& tooltip, + const QIcon& desc, const QString& paneName, const QString& contentDescription); -private: QString id; + /** + * @see IWorkbenchPart + */ + virtual void AddPropertyListener(IPropertyChangeListener* listener) override; -private: bool pinned; + /** + * @see IWorkbenchPart + */ + virtual void RemovePropertyListener(IPropertyChangeListener* listener) override; -private: QString tooltip; + QString GetId() const override; -/** - * Stores the current Image for this part reference. Lazily created. Null if not allocated. - */ -private: void* image; + virtual QString GetTitleToolTip() const override; -private: SmartPointer defaultImageDescriptor; + /** + * Returns the pane name for the part + * + * @return the pane name for the part + */ + virtual QString GetPartName() const override; - /** - * Stores the current image descriptor for the part. - */ -private: SmartPointer imageDescriptor; + /** + * Returns the content description for this part. + * + * @return the pane name for the part + */ + virtual QString GetContentDescription() const override; - /** - * API listener list - */ -private: IPropertyChangeListener::Events propChangeEvents; + virtual bool IsDirty() const override; -//private: ListenerList partChangeListeners = new ListenerList(); + virtual QIcon GetTitleImage() const override; -private: QString partName; + virtual void FireVisibilityChange(); -private: QString contentDescription; + virtual bool GetVisible(); -protected: QHash propertyCache; + virtual void SetVisible(bool isVisible); - /** - * Used to remember which events have been queued. - */ -private: QSet queuedEvents; + IWorkbenchPart::Pointer GetPart(bool restore) override; -private: bool queueEvents; + /** + * Returns the part pane for this part reference. Does not return null. + * + * @return + */ + SmartPointer GetPane(); -//private: static DisposeListener prematureDisposeListener = new DisposeListener() { -// public void widgetDisposed(DisposeEvent e) { -// WorkbenchPlugin.log(new RuntimeException("Widget disposed too early!")); //$NON-NLS-1$ -// } -// }; + void Dispose(); -private: + virtual void SetPinned(bool newPinned); - struct PropertyChangeListener : public IPropertyChangeListener - { - PropertyChangeListener(WorkbenchPartReference* ref); - using IPropertyChangeListener::PropertyChange; - void PropertyChange(const PropertyChangeEvent::Pointer& event); + virtual bool IsPinned() const override; - private: WorkbenchPartReference* partRef; - }; + /* + * @see org.blueberry.ui.IWorkbenchPartReference#getPartProperty(java.lang.String) + */ + virtual QString GetPartProperty(const QString& key) const override; -private: QScopedPointer propertyChangeListener; + int ComputePreferredSize(bool width, int availableParallel, + int availablePerpendicular, int preferredResult); -/** - * Calling this with deferEvents(true) will queue all property change events until a subsequent - * call to deferEvents(false). This should be used at the beginning of a batch of related changes - * to prevent duplicate property change events from being sent. - * - * @param shouldQueue - */ -private: void DeferEvents(bool shouldQueue); + int GetSizeFlags(bool width) override; -public: WorkbenchPartReference(); +protected: -public: ~WorkbenchPartReference(); + IWorkbenchPart::Pointer part; -public: virtual bool IsDisposed() const; + SmartPointer pane; -protected: virtual void CheckReference(); + QHash propertyCache; - /** - * Calling this with deferEvents(true) will queue all property change events until a subsequent - * call to deferEvents(false). This should be used at the beginning of a batch of related changes - * to prevent duplicate property change events from being sent. - * - * @param shouldQueue - */ -//private: virtual void DeferEvents(bool shouldQueue); + virtual void CheckReference(); -protected: virtual void SetPartName(const QString& newPartName); + virtual void SetPartName(const QString& newPartName); -protected: virtual void SetContentDescription(const QString& newContentDescription); + virtual void SetContentDescription(const QString& newContentDescription); -protected: virtual void SetImageDescriptor(SmartPointer descriptor); + virtual void SetImageDescriptor(const QIcon& descriptor); -protected: virtual void SetToolTip(const QString& newToolTip); + virtual void SetToolTip(const QString& newToolTip); -protected: virtual void PropertyChanged(const Object::Pointer& source, int propId); + virtual void PropertyChanged(const Object::Pointer& source, int propId); -protected: virtual void PropertyChanged(const PropertyChangeEvent::Pointer& event); + virtual void PropertyChanged(const PropertyChangeEvent::Pointer& event); - /** - * Refreshes all cached values with the values from the real part - */ -protected: virtual void RefreshFromPart(); + /** + * Refreshes all cached values with the values from the real part + */ + virtual void RefreshFromPart(); -protected: virtual SmartPointer ComputeImageDescriptor(); + virtual QIcon ComputeImageDescriptor(); -public: virtual void Init(const QString& id, const QString& tooltip, - SmartPointer desc, const QString& paneName, const QString& contentDescription); + // /* package */ virtual void fireZoomChange(); + QString GetRawToolTip() const; - /** - * @see IWorkbenchPart - */ -public: virtual void AddPropertyListener(IPropertyChangeListener* listener); + /** + * Gets the part name directly from the associated workbench part, + * or the empty string if none. + * + * @return + */ + QString GetRawPartName() const; - /** - * @see IWorkbenchPart - */ -public: virtual void RemovePropertyListener(IPropertyChangeListener* listener); + virtual QString ComputePartName() const; -public: QString GetId() const; + /** + * Computes a new content description for the part. Subclasses may override to change the + * default behavior + * + * @return the new content description for the part + */ + virtual QString ComputeContentDescription() const; -public: virtual QString GetTitleToolTip() const; + /** + * Returns the content description as set directly by the part, or the empty string if none + * + * @return the unmodified content description from the part (or the empty string if none) + */ + QString GetRawContentDescription() const; -protected: QString GetRawToolTip() const; + virtual void FirePropertyChange(int id); - /** - * Returns the pane name for the part - * - * @return the pane name for the part - */ -public: virtual QString GetPartName() const; + virtual IWorkbenchPart::Pointer CreatePart() = 0; - /** - * Gets the part name directly from the associated workbench part, - * or the empty string if none. - * - * @return - */ -protected: QString GetRawPartName() const; + virtual SmartPointer CreatePane() = 0; -protected: virtual QString ComputePartName() const; + void DoDisposePart(); - /** - * Returns the content description for this part. - * - * @return the pane name for the part - */ -public: virtual QString GetContentDescription() const; + virtual void FirePropertyChange(const PropertyChangeEvent::Pointer& event); - /** - * Computes a new content description for the part. Subclasses may override to change the - * default behavior - * - * @return the new content description for the part - */ -protected: virtual QString ComputeContentDescription() const; + virtual void CreatePartProperties(IWorkbenchPart::Pointer workbenchPart); - /** - * Returns the content description as set directly by the part, or the empty string if none - * - * @return the unmodified content description from the part (or the empty string if none) - */ -protected: QString GetRawContentDescription() const; +private: -public: virtual bool IsDirty() const; + /** + * Current state of the reference. Used to detect recursive creation errors, disposed + * references, etc. + */ + int state; -public: virtual void* GetTitleImage(); + QString id; -public: virtual SmartPointer GetTitleImageDescriptor() const; + bool pinned; -public: virtual void FireVisibilityChange(); + QString tooltip; -// /* package */ virtual void fireZoomChange(); + QIcon defaultImageDescriptor; -public: virtual bool GetVisible(); + /** + * Stores the current image descriptor for the part. + */ + QIcon imageDescriptor; -public: virtual void SetVisible(bool isVisible); + /** + * API listener list + */ + IPropertyChangeListener::Events propChangeEvents; + + //private: ListenerList partChangeListeners = new ListenerList(); + + QString partName; + + QString contentDescription; -protected: virtual void FirePropertyChange(int id); + /** + * Used to remember which events have been queued. + */ + QSet queuedEvents; + + bool queueEvents; -private: void ImmediateFirePropertyChange(int id); +//static DisposeListener prematureDisposeListener = new DisposeListener() { +// public void widgetDisposed(DisposeEvent e) { +// WorkbenchPlugin.log(new RuntimeException("Widget disposed too early!")); //$NON-NLS-1$ +// } +// }; -public: IWorkbenchPart::Pointer GetPart(bool restore); + struct PropertyChangeListener : public IPropertyChangeListener + { + PropertyChangeListener(WorkbenchPartReference* ref); + using IPropertyChangeListener::PropertyChange; + void PropertyChange(const PropertyChangeEvent::Pointer& event); -protected: virtual IWorkbenchPart::Pointer CreatePart() = 0; + private: + WorkbenchPartReference* partRef; + }; -protected: virtual SmartPointer CreatePane() = 0; + QScopedPointer propertyChangeListener; - /** - * Returns the part pane for this part reference. Does not return null. - * - * @return - */ -public: SmartPointer GetPane(); + /** + * Calling this with deferEvents(true) will queue all property change events until a subsequent + * call to deferEvents(false). This should be used at the beginning of a batch of related changes + * to prevent duplicate property change events from being sent. + * + * @param shouldQueue + */ + void DeferEvents(bool shouldQueue); -public: void Dispose(); + void ImmediateFirePropertyChange(int id); /** * Clears all of the listeners in a listener list. TODO Bug 117519 Remove * this method when fixed. * * @param list * The list to be clear; must not be null. */ -//private: void clearListenerList(const ListenerList list); - - -public: virtual void SetPinned(bool newPinned); - -public: virtual bool IsPinned() const; - -protected: void DoDisposePart(); - -/* (non-Javadoc) - * @see org.blueberry.ui.IWorkbenchPartReference#getPartProperty(java.lang.String) - */ -public: virtual QString GetPartProperty(const QString& key) const; - -protected: virtual void FirePropertyChange(const PropertyChangeEvent::Pointer& event); - -protected: virtual void CreatePartProperties(IWorkbenchPart::Pointer workbenchPart); - -public: int ComputePreferredSize(bool width, int availableParallel, - int availablePerpendicular, int preferredResult); - -public: int GetSizeFlags(bool width); + //private: void clearListenerList(const ListenerList list); }; } // namespace berry #endif /*BERRYWORKBENCHPARTREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp index 758b2e737a..33a37a1805 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp @@ -1,396 +1,393 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbench.h" #include "berryPlatform.h" #include "intro/berryEditorIntroAdapterPart.h" #include "defaultpresentation/berryQtWorkbenchPresentationFactory.h" #include "berryQtStyleManager.h" #include "berryQtDnDTweaklet.h" -#include "berryQtImageTweaklet.h" #include "berryQtWorkbenchTweaklet.h" #include "berryQtWorkbenchPageTweaklet.h" #include "berryQtWidgetsTweaklet.h" #include "berryQtStylePreferencePage.h" #include "berryStatusUtil.h" #include "berryHandlerServiceFactory.h" #include "berryMenuServiceFactory.h" #include "berryCommandServiceFactory.h" #include "berryWorkbenchSourceProvider.h" #include "berryObjectString.h" #include "berryObjects.h" #include "berryShowViewHandler.h" #include "berryIQtStyleManager.h" -#include "berryImageDescriptor.h" #include "berryIContributor.h" #include "berryILog.h" #include "berryIExtension.h" #include namespace berry { bool WorkbenchPlugin::DEBUG = false; char WorkbenchPlugin::PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/'; WorkbenchPlugin* WorkbenchPlugin::inst = 0; WorkbenchPlugin::WorkbenchPlugin() : AbstractUICTKPlugin() { inst = this; presentationFactory = 0; editorRegistry = 0; viewRegistry = 0; perspRegistry = 0; introRegistry = 0; } WorkbenchPlugin::~WorkbenchPlugin() { delete presentationFactory; delete editorRegistry; delete viewRegistry; delete perspRegistry; delete introRegistry; inst = 0; } bool WorkbenchPlugin::HasExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { if (!element->GetAttribute(extensionName).isNull()) return true; QString elementText = element->GetValue(); if (!elementText.isEmpty()) return true; QList children(element->GetChildren(extensionName)); if (children.size() == 1) { if (!(children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isNull())) return true; } return false; } bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { QSharedPointer plugin = WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName); if (plugin.isNull()) return true; return plugin->getState() == ctkPlugin::ACTIVE; } QSharedPointer WorkbenchPlugin::GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { // this code is derived heavily from // ConfigurationElement.createExecutableExtension. QString prop; QString executable; QString contributorName; int i = 0; if (!extensionName.isNull()) prop = element->GetAttribute(extensionName); else { // property not specified, try as element value prop = element->GetValue(); if (!prop.isNull()) { prop = prop.trimmed(); if (prop.isEmpty()) prop = QString(); } } if (prop.isNull()) { // property not defined, try as a child element QList exec(element->GetChildren(extensionName)); if (!exec.isEmpty()) contributorName = exec[0]->GetAttribute("plugin"); } else { // simple property or element value, parse it into its components i = prop.indexOf(':'); if (i != -1) executable = prop.left(i).trimmed(); else executable = prop; i = executable.indexOf('/'); if (i != -1) contributorName = executable.left(i).trimmed(); } if (contributorName.isNull()) contributorName = element->GetContributor()->GetName(); return Platform::GetPlugin(contributorName); } WorkbenchPlugin* WorkbenchPlugin::GetDefault() { return inst; } std::size_t WorkbenchPlugin::GetBundleCount() { // TODO BundleContext GetBundles //return bundleContext->GetBundles().size(); return 0; } // ImageRegistry createImageRegistry() { // return WorkbenchImages.getImageRegistry(); // } IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry() { if (perspRegistry == 0) { perspRegistry = new PerspectiveRegistry(); // the load methods can touch on WorkbenchImages if an image is // missing so we need to wrap the call in // a startup block for the case where a custom descriptor exists on // startup that does not have an image // associated with it. See bug 196352. //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { perspRegistry->Load(); // } //}); } return perspRegistry; } // PreferenceManager getPreferenceManager() { // if (preferenceManager == null) { // preferenceManager = new WorkbenchPreferenceManager( // PREFERENCE_PAGE_CATEGORY_SEPARATOR); // // //Get the pages from the registry // PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader( // getWorkbench()); // registryReader // .loadFromRegistry(Platform.getExtensionRegistry()); // preferenceManager.addPages(registryReader.getTopLevelNodes()); // // } // return preferenceManager; // } // ISharedImages getSharedImages() { // if (sharedImages == null) { // sharedImages = new SharedImages(); // } // return sharedImages; // } IIntroRegistry* WorkbenchPlugin::GetIntroRegistry() { if (introRegistry == 0) { introRegistry = new IntroRegistry(); } return introRegistry; } IViewRegistry* WorkbenchPlugin::GetViewRegistry() { if (!viewRegistry) viewRegistry = new ViewRegistry(); return viewRegistry; } IEditorRegistry* WorkbenchPlugin::GetEditorRegistry() { if (!editorRegistry) editorRegistry = new EditorRegistry(); return editorRegistry; } IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() { if (presentationFactory != 0) return presentationFactory; QString targetID = Workbench::GetInstance()->GetPresentationId(); presentationFactory = this->CreateExtension( WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, "factory", targetID); if (presentationFactory == 0) WorkbenchPlugin::Log("Error creating presentation factory: " + targetID + " -- class is not an IPresentationFactory"); return presentationFactory; } void WorkbenchPlugin::Log(const QString& message) { BERRY_INFO << "LOG: " << message << std::endl; //inst->GetLog().log(message); } void WorkbenchPlugin::Log(const ctkException &exc) { QString str; QDebug dbg(&str); dbg << exc.printStackTrace(); BERRY_INFO << "LOG: " << str << std::endl; //inst->GetLog().log(exc); } void WorkbenchPlugin::Log(const QString& message, const ctkException &t) { PlatformException exc(message, t); WorkbenchPlugin::Log(exc); } void WorkbenchPlugin::Log(const QString& clazz, const QString& methodName, const ctkException &t) { QString msg = QString("Exception in ") + clazz + "." + methodName + ": " + t.what(); WorkbenchPlugin::Log(msg, t); } void WorkbenchPlugin::Log(const QString& message, const SmartPointer& status) { //1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info if (!message.isEmpty()) { GetDefault()->GetLog()->Log(StatusUtil::NewStatus(IStatus::ERROR_TYPE, message, BERRY_STATUS_LOC)); } GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::Log(const SmartPointer& status) { GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::start(ctkPluginContext* context) { //context.addBundleListener(getBundleListener()); AbstractUICTKPlugin::start(context); bundleContext = context; BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context) BERRY_REGISTER_EXTENSION_CLASS(QtDnDTweaklet, context) - BERRY_REGISTER_EXTENSION_CLASS(QtImageTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWidgetsTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPageTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPresentationFactory, context) BERRY_REGISTER_EXTENSION_CLASS(QtStylePreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(HandlerServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(MenuServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(CommandServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(WorkbenchSourceProvider, context) BERRY_REGISTER_EXTENSION_CLASS(ShowViewHandler, context) styleManager.reset(new QtStyleManager()); context->registerService(styleManager.data()); // The UI plugin needs to be initialized so that it can install the callback in PrefUtil, // which needs to be done as early as possible, before the workbench // accesses any API preferences. // Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID); // try // { // // Attempt to load the activator of the ui bundle. This will force lazy start // // of the ui bundle. Using the bundle activator class here because it is a // // class that needs to be loaded anyway so it should not cause extra classes // // to be loaded. // if(uiBundle != null) // uiBundle.loadClass(UI_BUNDLE_ACTIVATOR); // } // catch (ClassNotFoundException e) // { // WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$ // } /* * DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are * likely to cause a deadlock in class loader code. Please see Bug 86450 * for more information. */ } //const QList WorkbenchPlugin::GetBundles() //{ // return bundleContext.IsNull() ? QList() : bundleContext->GetBundles(); //} ctkPluginContext* WorkbenchPlugin::GetPluginContext() { return bundleContext; } void WorkbenchPlugin::stop(ctkPluginContext* context) { AbstractUICTKPlugin::stop(context); styleManager.reset(); delete perspRegistry; // avoid possible crash, see bug #18399 perspRegistry = 0; } QString WorkbenchPlugin::GetDataLocation() const { QFileInfo fileInfo = bundleContext->getDataFile(""); if (!fileInfo.isWritable()) return QString(); return fileInfo.absoluteFilePath(); } } Q_EXPORT_PLUGIN2(org_blueberry_ui_qt, berry::WorkbenchPlugin) diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchServiceRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchServiceRegistry.cpp index 3ec1b0c9f8..22330d0aac 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchServiceRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchServiceRegistry.cpp @@ -1,270 +1,269 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "berryWorkbenchServiceRegistry.h" #include "berryISources.h" #include "berryISourceProvider.h" #include "berryPlatformUI.h" -#include "berryImageDescriptor.h" #include "services/berryIServiceFactory.h" #include "berryServiceLocator.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berrySourcePriorityNameMapping.h" #include "berryAbstractSourceProvider.h" #include "berryStatus.h" #include "berryPlatformUI.h" namespace berry { const QString WorkbenchServiceRegistry::WORKBENCH_LEVEL = "workbench"; const QString WorkbenchServiceRegistry::EXT_ID_SERVICES = "org.blueberry.ui.services"; //$NON-NLS-1$ const IServiceLocator::Pointer WorkbenchServiceRegistry::GLOBAL_PARENT = IServiceLocator::Pointer(new GlobalParentLocator()); QStringList WorkbenchServiceRegistry::SupportedLevels() { struct _Levels { QStringList levels; _Levels() { levels << ISources::ACTIVE_CONTEXT_NAME() << ISources::ACTIVE_SHELL_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_NAME() << ISources::ACTIVE_EDITOR_ID_NAME() << ISources::ACTIVE_PART_ID_NAME() << ISources::ACTIVE_SITE_NAME(); } }; static _Levels _levels; return _levels.levels; } WorkbenchServiceRegistry::WorkbenchServiceRegistry() { // PlatformUI::GetWorkbench().getExtensionTracker().registerHandler(this, // ExtensionTracker .createExtensionPointFilter(getExtensionPoint())); } WorkbenchServiceRegistry::ServiceFactoryHandle::ServiceFactoryHandle( const IServiceFactory* _factory) : factory(_factory) { } WorkbenchServiceRegistry::ServiceFactoryHandle::Pointer WorkbenchServiceRegistry::LoadFromRegistry( const QString& key) { ServiceFactoryHandle::Pointer result; const QList serviceFactories = this->GetExtensionPoint()->GetConfigurationElements(); try { bool done = false; for (int i = 0; i < serviceFactories.size() && !done; i++) { QList serviceNameElements = serviceFactories[i]->GetChildren( WorkbenchRegistryConstants::TAG_SERVICE); for (int j = 0; j < serviceNameElements.size() && !done; j++) { QString serviceName = serviceNameElements[j]->GetAttribute( WorkbenchRegistryConstants::ATTR_SERVICE_CLASS); if (key == serviceName) { done = true; } } if (done) { IServiceFactory* f = serviceFactories[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_FACTORY_CLASS); ServiceFactoryHandle::Pointer handle(new ServiceFactoryHandle(f)); // PlatformUI.getWorkbench().getExtensionTracker().registerObject( // serviceFactories[i].getDeclaringExtension(), handle, // IExtensionTracker.REF_WEAK); QList serviceNames; for (int j = 0; j < serviceNameElements.size(); j++) { QString serviceName = serviceNameElements[j]->GetAttribute( WorkbenchRegistryConstants::ATTR_SERVICE_CLASS); if (factories.find(serviceName) != factories.end()) { WorkbenchPlugin::Log("Factory already exists for " + serviceName); } else { factories.insert(serviceName, handle); serviceNames.push_back(serviceName); } } handle->serviceNames = serviceNames; result = handle; } } } catch (const CoreException& e) { //StatusManager.getManager().handle(e.getStatus()); BERRY_ERROR << "CoreException: " << e.what() << std::endl; } return result; } IExtensionPoint::Pointer WorkbenchServiceRegistry::GetExtensionPoint() const { IExtensionRegistry* reg = Platform::GetExtensionRegistry(); return reg->GetExtensionPoint(EXT_ID_SERVICES); } void WorkbenchServiceRegistry::ProcessVariables( const QList& children) const { for (int i = 0; i < children.size(); i++) { QString name = children[i]->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); if (name.isEmpty()) { continue; } QString level = children[i]->GetAttribute(WorkbenchRegistryConstants::ATT_PRIORITY_LEVEL); if (level.isEmpty()) { level = WORKBENCH_LEVEL; } else { bool found = false; QStringList supportedLevels = this->SupportedLevels(); for (int j = 0; j < supportedLevels.size() && !found; j++) { if (supportedLevels[j] == level) { found = true; } } if (!found) { level = WORKBENCH_LEVEL; } } int existingPriority = SourcePriorityNameMapping::GetMapping(level); int newPriority = existingPriority << 1; SourcePriorityNameMapping::AddMapping(name, newPriority); } } Object* WorkbenchServiceRegistry::GlobalParentLocator::GetService( const QString& /*api*/) { return NULL; } bool WorkbenchServiceRegistry::GlobalParentLocator::HasService( const QString& /*api*/) const { return false; } WorkbenchServiceRegistry* WorkbenchServiceRegistry::GetRegistry() { static WorkbenchServiceRegistry registry; return ®istry; } Object::Pointer WorkbenchServiceRegistry::GetService(const QString& key, IServiceLocator* parentLocator, ServiceLocator* locator) { ServiceFactoryHandle::Pointer handle = factories.value(key); if (!handle) { handle = this->LoadFromRegistry(key); } if (handle) { Object::Pointer result(handle->factory->Create(key, parentLocator, locator)); if (result) { //handle->serviceLocators.insert(locator, new Object()); return result; } } return Object::Pointer(0); } QList WorkbenchServiceRegistry::GetSourceProviders() const { QList providers; IExtensionPoint::Pointer ep = this->GetExtensionPoint(); QList elements = ep->GetConfigurationElements(); for (int i = 0; i < elements.size(); i++) { if (elements[i]->GetName() == WorkbenchRegistryConstants::TAG_SOURCE_PROVIDER) { try { ISourceProvider* sourceProvider(elements[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_PROVIDER)); if (AbstractSourceProvider* asp = dynamic_cast(sourceProvider)) { providers.push_back(AbstractSourceProvider::Pointer(asp)); } else { const QString attributeName = elements[i]->GetAttribute(WorkbenchRegistryConstants::ATTR_PROVIDER); const QString message = "Source Provider '" + attributeName + "' should extend AbstractSourceProvider"; const IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), message, BERRY_STATUS_LOC)); WorkbenchPlugin::Log(status); continue; } } catch (const CoreException& e) { //StatusManager.getManager().handle(e.getStatus()); BERRY_ERROR << "CoreException: " << e.what() << std::endl; } } } return providers; } void WorkbenchServiceRegistry::InitializeSourcePriorities() { IExtensionPoint::Pointer ep = GetExtensionPoint(); QList elements = ep->GetConfigurationElements(); for (int i = 0; i < elements.size(); i++) { if (elements[i]->GetName() == WorkbenchRegistryConstants::TAG_SOURCE_PROVIDER) { ProcessVariables(elements[i]->GetChildren(WorkbenchRegistryConstants::TAG_VARIABLE)); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp index 70a3875594..7800248421 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp @@ -1,296 +1,295 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" -#include "berryImageDescriptor.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryEditorSashContainer.h" #include "berryWorkbenchPlugin.h" #include "berryMenuManager.h" #include "berryQtDnDControlWidget.h" namespace berry { WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd) : window(wnd) { } void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy) { this->proxy = proxy; } IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer() { return WorkbenchWindow::Pointer(window)->GetWindowConfigurer(); } IMenuManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager() { if (proxy.IsNotNull()) { return proxy->GetMenuManager(); } return window.Lock()->GetMenuManager(); } IToolBarManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetToolBarManager() { if (proxy.IsNotNull()) { return proxy->GetToolBarManager(); } //return window.Lock()->GetToolBarManager(); return 0; } WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(const WorkbenchWindow::Pointer& window) : shellStyle(0) , showPerspectiveBar(false) , showStatusLine(true) , showToolBar(true) , showMenuBar(true) , showProgressIndicator(false) , dropTargetListener(NULL) , initialSize(1024,768) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } this->window = window; windowTitle = "BlueBerry Application"; } IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow() { return IWorkbenchWindow::Pointer(window); } IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer() { return dynamic_cast(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer(); } QString WorkbenchWindowConfigurer::BasicGetTitle() { return windowTitle; } QString WorkbenchWindowConfigurer::GetTitle() { Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { // update the cached title windowTitle = shell->GetText(); } return windowTitle; } void WorkbenchWindowConfigurer::SetTitle(const QString &title) { windowTitle = title; Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { shell->SetText(title); } } bool WorkbenchWindowConfigurer::GetShowMenuBar() const { return showMenuBar; } void WorkbenchWindowConfigurer::SetShowMenuBar(bool show) { showMenuBar = show; // WorkbenchWindow win = (WorkbenchWindow) getWindow(); // Shell shell = win.getShell(); // if (shell != null) // { // boolean showing = shell.getMenuBar() != null; // if (show != showing) // { // if (show) // { // shell.setMenuBar(win.getMenuBarManager().getMenu()); // } // else // { // shell.setMenuBar(null); // } // } // } } bool WorkbenchWindowConfigurer::GetShowToolBar() const { return showToolBar; } void WorkbenchWindowConfigurer::SetShowToolBar(bool show) { showToolBar = show; //window.setCoolBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() const { return showPerspectiveBar; } void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show) { showPerspectiveBar = show; //window.setPerspectiveBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowStatusLine() const { return showStatusLine; } void WorkbenchWindowConfigurer::SetShowStatusLine(bool show) { showStatusLine = show; // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowProgressIndicator() const { return showProgressIndicator; } void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show) { showProgressIndicator = show; // @issue need to be able to reconfigure after window's controls created } void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers) { if (transfers.isEmpty()) return; int oldSize = transferTypes.size(); transferTypes.unite(QSet::fromList(transfers)); if (transferTypes.size() == oldSize) return; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->SetTransferTypes(transferTypes.toList()); } } void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(IDropTargetListener* listener) { if (listener == 0) return; dropTargetListener = listener; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->AddDropListener(listener); } } QStringList WorkbenchWindowConfigurer::GetTransfers() const { return transferTypes.toList(); } IDropTargetListener* WorkbenchWindowConfigurer::GetDropTargetListener() const { return dropTargetListener; } IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer() { if (actionBarConfigurer.IsNull()) { // lazily initialize actionBarConfigurer = new WindowActionBarConfigurer(window); } return actionBarConfigurer; } Qt::WindowFlags WorkbenchWindowConfigurer::GetWindowFlags() const { return shellStyle; } void WorkbenchWindowConfigurer::SetWindowFlags(Qt::WindowFlags shellStyle) { this->shellStyle = shellStyle; } Point WorkbenchWindowConfigurer::GetInitialSize() const { return initialSize; } void WorkbenchWindowConfigurer::SetInitialSize(Point size) { initialSize = size; } void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell) { WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell); } QMenuBar* WorkbenchWindowConfigurer::CreateMenuBar() { return window.Lock()->GetMenuManager()->CreateMenuBar(window.Lock()->GetShell()->GetControl()); } QWidget* WorkbenchWindowConfigurer::CreateToolBar(QWidget* /*parent*/) { // IToolBarManager* toolBarManager = window->GetToolBarManager(); // if (toolBarManager) // { // return toolBarManager->CreateControl(parent); // } return 0; } QWidget *WorkbenchWindowConfigurer::CreatePageComposite(QWidget *parent) { return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent); } bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento) { return WorkbenchWindow::Pointer(window)->SaveState(memento); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.cpp index 3de8a93af4..4a6981972f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.cpp @@ -1,137 +1,129 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryNativeTabItem.h" #include "berryNativeTabFolder.h" #include "berryQCTabBar.h" #include #include namespace berry { NativeTabItem::NativeTabItem(NativeTabFolder* _parent, int index, int flags) : parent(_parent), style(flags), showClose(true), closeButton(0) { parent->GetTabFolder()->insertTab(index, this); #if QT_VERSION >= 0x040500 if (this->GetShowClose()) { parent->GetTabFolder()->setTabButton(index, QTabBar::RightSide, this->GetCloseButton()); this->connect(this->GetCloseButton(), SIGNAL(clicked()), this, SLOT(CloseButtonClicked())); } #endif } void NativeTabItem::CloseButtonClicked() { parent->CloseButtonClicked(this); } QRect NativeTabItem::GetBounds() { int index = parent->IndexOf(this); QTabBar* folder = parent->GetTabFolder(); QRect localRect = folder->tabRect(index); QPoint topLeft = localRect.topLeft(); QPoint bottomRight = localRect.bottomRight(); QPoint globalTopLeft = folder->mapToGlobal(topLeft); QPoint globalBottomRight = folder->mapToGlobal(bottomRight); return QRect(globalTopLeft, globalBottomRight); } void NativeTabItem::SetInfo(const PartInfo& info) { QTabBar* widget = parent->GetTabFolder(); int index = parent->IndexOf(this); if (widget->tabText(index) != info.name) { widget->setTabText(index, info.name); } if (widget->tabToolTip(index) != info.toolTip) { widget->setTabToolTip(index, info.toolTip); } - if (info.image == 0) + if (widget->tabIcon(index).cacheKey() != info.image.cacheKey()) { - widget->setTabIcon(index, QIcon()); - } - else - { - QIcon icon(*(info.image)); - if (widget->tabIcon(index).cacheKey() != icon.cacheKey()) - { - widget->setTabIcon(index, icon); - } + widget->setTabIcon(index, info.image); } } bool NativeTabItem::GetShowClose() const { return ((style & Constants::CLOSE) && showClose); } void NativeTabItem::SetShowClose(bool close) { showClose = close; } QWidget* NativeTabItem::GetCloseButton() { if (!closeButton) { QIcon iconCloseTab( ":/org.blueberry.ui.qt/tab_close_icon.png" ); iconCloseTab.addFile(":/org.blueberry.ui.qt/tab_close_icon-active.png", QSize(), QIcon::Active); closeButton = new QToolButton(parent->GetControl()); closeButton->setObjectName("TabCloseButton"); closeButton->setContentsMargins(0, 0, 0, 0); closeButton->setFixedSize(12,12); //closeButton->setFlat(true); closeButton->setIcon(iconCloseTab); closeButton->setAutoRaise(true); } return closeButton; } void NativeTabItem::Dispose() { QTabBar* widget = parent->GetTabFolder(); int index = parent->IndexOf(this); widget->removeTab(index); // this calls QCTabBar::tabRemoved } Object::Pointer NativeTabItem::GetData() { return data; } void NativeTabItem::SetData(Object::Pointer d) { this->data = d; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp index 477ce11a11..5a84c743e7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp @@ -1,141 +1,141 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEditorIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { EditorIntroAdapterPart::EditorIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &EditorIntroAdapterPart::PropertyChange)) { } void EditorIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void EditorIntroAdapterPart::CreatePartControl(void* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } EditorIntroAdapterPart::~EditorIntroAdapterPart() { //setBarVisibility(true); if(introPart) { introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } } -void* EditorIntroAdapterPart::GetTitleImage() const +QIcon EditorIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString EditorIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? EditorPart::GetPartName() : introPart->GetPartName(); } void EditorIntroAdapterPart::Init(IEditorSite::Pointer site, IEditorInput::Pointer input) { Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager()->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, IMemento::Pointer(0)); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro editor proxy.", e); } this->SetSite(site); this->SetInput(input); } void EditorIntroAdapterPart::DoSave(/*IProgressMonitor monitor*/) { } void EditorIntroAdapterPart::DoSaveAs() { } bool EditorIntroAdapterPart::IsDirty() const { return false; } bool EditorIntroAdapterPart::IsSaveAsAllowed() const { return false; } void EditorIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void EditorIntroAdapterPart::SetFocus() { introPart->SetFocus(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h index bf7e4f8924..ac005a0adc 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h @@ -1,159 +1,159 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEDITORINTROADAPTERPART_H_ #define BERRYEDITORINTROADAPTERPART_H_ #include #include #include namespace berry { /** * Simple editor that will wrap an IIntroPart. */ class EditorIntroAdapterPart: public EditorPart { Q_OBJECT private: IIntroPart::Pointer introPart; IIntroSite::Pointer introSite; QScopedPointer propChangeListener; friend struct PropertyChangeIntAdapter ; void PropertyChange(const Object::Pointer& source, int propId); // bool handleZoomEvents = true; // /** // * Adds a listener that toggles standby state if the view pane is zoomed. // */ // void AddPaneListener() { // IWorkbenchPartSite site = getSite(); // if (site instanceof PartSite) { // final WorkbenchPartReference ref = ((WorkbenchPartReference)((PartSite) site).getPartReference()); // ref.addInternalPropertyListener( // new IPropertyListener() { // public void propertyChanged(Object source, int propId) { // if (handleZoomEvents) { // if (propId == WorkbenchPartReference.INTERNAL_PROPERTY_ZOOMED) { // setStandby(!ref.getPane().isZoomed()); // } // } // } // }); // } // } // /** // * Sets whether the CoolBar/PerspectiveBar should be visible. // * // * @param visible whether the CoolBar/PerspectiveBar should be visible // */ // void SetBarVisibility(bool visible) { // WorkbenchWindow window = (WorkbenchWindow) getSite() // .getWorkbenchWindow(); // // final boolean layout = (visible != window.getCoolBarVisible()) // || (visible != window.getPerspectiveBarVisible()); // don't layout unless things have actually changed // if (visible) { // window.setCoolBarVisible(true); // window.setPerspectiveBarVisible(true); // } else { // window.setCoolBarVisible(false); // window.setPerspectiveBarVisible(false); // } // // if (layout) { // window.getShell().layout(); // } // } public: EditorIntroAdapterPart(); /** * Forces the standby state of the intro part. * * @param standby update the standby state */ void SetStandby(bool standby); // /** // * Toggles handling of zoom events. // * // * @param handle whether to handle zoom events // */ // void SetHandleZoomEvents(boolean handle) { // handleZoomEvents = handle; // } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ void CreatePartControl(void* parent); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ ~EditorIntroAdapterPart(); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#getTitleImage() */ - void* GetTitleImage() const; + QIcon GetTitleImage() const; /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#GetPartName() */ QString GetPartName() const; void Init(IEditorSite::Pointer site, IEditorInput::Pointer input); void DoSave(/*IProgressMonitor monitor*/); void DoSaveAs(); bool IsDirty() const; bool IsSaveAsAllowed() const; /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento) */ void SaveState(IMemento::Pointer memento); }; } #endif /* BERRYEDITORINTROADAPTERPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIIntroDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIIntroDescriptor.h index 2032d5c6dd..9fa5fed015 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIIntroDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIIntroDescriptor.h @@ -1,78 +1,76 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIINTRODESCRIPTOR_H_ #define BERRYIINTRODESCRIPTOR_H_ #include #include #include "intro/berryIIntroPart.h" -#include - namespace berry { /** * Describes an introduction extension. * * @since 3.0 */ struct BERRY_UI_QT IIntroDescriptor : public Object { berryObjectMacro(berry::IIntroDescriptor) ~IIntroDescriptor(); /** * Creates an instance of the intro part defined in the descriptor. */ virtual IIntroPart::Pointer CreateIntro() = 0; /** * Returns the role of the intro part (view or editor) * @return the role of the part */ virtual int GetRole() const = 0; /** * Returns the part id. * * @return the id of the part */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image for this part. * * @return the descriptor of the image to display next to this part */ - virtual ImageDescriptor::Pointer GetImageDescriptor() const = 0; + virtual QIcon GetImageDescriptor() const = 0; /** * Return the label override string for this part. * * @return the label override string or the empty string if one has not * been specified */ virtual QString GetLabelOverride() const = 0; }; } #endif /* BERRYIINTRODESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.cpp index b091e2c209..f80335a575 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.cpp @@ -1,110 +1,109 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIntroDescriptor.h" #include "berryIntroConstants.h" #include "internal/berryWorkbenchRegistryConstants.h" #include #include #include #include namespace berry { IntroDescriptor::IntroDescriptor(IConfigurationElement::Pointer configElement) : element(configElement) { QString val = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS); if (val.isEmpty()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, configElement->GetContributor()->GetName(), 0, QString("Invalid extension (Missing class name): ") + GetId())); throw CoreException(status); } } SmartPointer IntroDescriptor::CreateIntro() { IIntroPart::Pointer intro(element->CreateExecutableExtension(WorkbenchRegistryConstants::ATT_CLASS)); return intro; } IntroContentDetector::Pointer IntroDescriptor::GetIntroContentDetector() { QString val = element->GetAttribute(WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR); if (val.isEmpty()) { return IntroContentDetector::Pointer(0); } IntroContentDetector::Pointer detector( element->CreateExecutableExtension(WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR)); return detector; } int IntroDescriptor::GetRole() const { QString role = element->GetAttribute(WorkbenchRegistryConstants::ATT_ROLE); if (role.isEmpty()) { return IntroConstants::INTRO_ROLE_VIEW; } if (role == "editor") return IntroConstants::INTRO_ROLE_EDITOR; else return IntroConstants::INTRO_ROLE_VIEW; } QString IntroDescriptor::GetId() const { return element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); } QString IntroDescriptor::GetPluginId() const { return element->GetContributor()->GetName(); } -ImageDescriptor::Pointer IntroDescriptor::GetImageDescriptor() const +QIcon IntroDescriptor::GetImageDescriptor() const { - if (imageDescriptor) + if (!imageDescriptor.isNull()) { return imageDescriptor; } QString iconName = element->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); if (iconName.isEmpty()) { - return ImageDescriptor::Pointer(); + return QIcon(); } - imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( + return AbstractUICTKPlugin::ImageDescriptorFromPlugin( element->GetContributor()->GetName(), iconName); - return imageDescriptor; } IConfigurationElement::Pointer IntroDescriptor::GetConfigurationElement() const { return element; } QString IntroDescriptor::GetLabelOverride() const { return element->GetAttribute(WorkbenchRegistryConstants::ATT_LABEL); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.h index 96c6cc1842..d248296861 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroDescriptor.h @@ -1,89 +1,90 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYINTRODESCRIPTOR_H_ #define BERRYINTRODESCRIPTOR_H_ #include "berryIIntroDescriptor.h" #include "intro/berryIntroContentDetector.h" #include "intro/berryIIntroPart.h" #include -#include + +#include namespace berry { /** * Describes an introduction extension. * */ class IntroDescriptor: public IIntroDescriptor { private: IConfigurationElement::Pointer element; - mutable ImageDescriptor::Pointer imageDescriptor; + mutable QIcon imageDescriptor; public: - berryObjectMacro(IntroDescriptor); + berryObjectMacro(IntroDescriptor) /** * Create a new IntroDescriptor for an extension. */ IntroDescriptor(IConfigurationElement::Pointer configElement); /* * @see IIntroDescriptor#CreateIntro() */ IIntroPart::Pointer CreateIntro(); IntroContentDetector::Pointer GetIntroContentDetector(); int GetRole() const; /* * @see IIntroDescriptor#GetId() */ QString GetId() const; QString GetPluginId() const; /* * @see IIntroDescriptor#GetImageDescriptor() */ - ImageDescriptor::Pointer GetImageDescriptor() const; + QIcon GetImageDescriptor() const; /** * Returns the configuration element. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* * @see IIntroDescriptor#GetLabelOverride() */ QString GetLabelOverride() const; }; } #endif /* BERRYINTRODESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp index 739727b951..feba83a59f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp @@ -1,121 +1,121 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { ViewIntroAdapterPart::ViewIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &ViewIntroAdapterPart::PropertyChange)) { } void ViewIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void ViewIntroAdapterPart::CreatePartControl(void* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } ViewIntroAdapterPart::~ViewIntroAdapterPart() { //setBarVisibility(true); introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } -void* ViewIntroAdapterPart::GetTitleImage() const +QIcon ViewIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString ViewIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? ViewPart::GetPartName() : introPart->GetPartName(); } void ViewIntroAdapterPart::Init(IViewSite::Pointer site, IMemento::Pointer memento) throw (PartInitException) { ViewPart::Init(site); Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager() ->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, memento); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro view proxy.", e); } } void ViewIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void ViewIntroAdapterPart::SetFocus() { introPart->SetFocus(); } void ViewIntroAdapterPart::SaveState(IMemento::Pointer memento) { introPart->SaveState(memento); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h index 0b6e3d1847..26420ca316 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h @@ -1,155 +1,155 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYVIEWINTROADAPTERPART_H_ #define BERRYVIEWINTROADAPTERPART_H_ #include #include #include namespace berry { /** * Simple view that will wrap an IIntroPart. * * @since 3.0 */ class ViewIntroAdapterPart: public ViewPart { private: IIntroPart::Pointer introPart; IIntroSite::Pointer introSite; QScopedPointer propChangeListener; friend struct PropertyChangeIntAdapter ; void PropertyChange(const Object::Pointer& source, int propId); // bool handleZoomEvents = true; // /** // * Adds a listener that toggles standby state if the view pane is zoomed. // */ // void AddPaneListener() { // IWorkbenchPartSite site = getSite(); // if (site instanceof PartSite) { // final WorkbenchPartReference ref = ((WorkbenchPartReference)((PartSite) site).getPartReference()); // ref.addInternalPropertyListener( // new IPropertyListener() { // public void propertyChanged(Object source, int propId) { // if (handleZoomEvents) { // if (propId == WorkbenchPartReference.INTERNAL_PROPERTY_ZOOMED) { // setStandby(!ref.getPane().isZoomed()); // } // } // } // }); // } // } // /** // * Sets whether the CoolBar/PerspectiveBar should be visible. // * // * @param visible whether the CoolBar/PerspectiveBar should be visible // */ // void SetBarVisibility(bool visible) { // WorkbenchWindow window = (WorkbenchWindow) getSite() // .getWorkbenchWindow(); // // final boolean layout = (visible != window.getCoolBarVisible()) // || (visible != window.getPerspectiveBarVisible()); // don't layout unless things have actually changed // if (visible) { // window.setCoolBarVisible(true); // window.setPerspectiveBarVisible(true); // } else { // window.setCoolBarVisible(false); // window.setPerspectiveBarVisible(false); // } // // if (layout) { // window.getShell().layout(); // } // } public: ViewIntroAdapterPart(); /** * Forces the standby state of the intro part. * * @param standby update the standby state */ void SetStandby(bool standby); // /** // * Toggles handling of zoom events. // * // * @param handle whether to handle zoom events // */ // void SetHandleZoomEvents(boolean handle) { // handleZoomEvents = handle; // } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ void CreatePartControl(void* parent); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ ~ViewIntroAdapterPart(); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#getTitleImage() */ - void* GetTitleImage() const; + QIcon GetTitleImage() const; /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#GetPartName() */ QString GetPartName() const; /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#init(org.eclipse.ui.IViewSite, org.eclipse.ui.IMemento) */ void Init(IViewSite::Pointer site, IMemento::Pointer memento = IMemento::Pointer(0)) throw (PartInitException); /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento) */ void SaveState(IMemento::Pointer memento); }; } #endif /* BERRYVIEWINTROADAPTERPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.cpp index 24b4bfa163..d534fb38a2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.cpp @@ -1,43 +1,41 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPartInfo.h" namespace berry { -PartInfo::PartInfo() : - image(0) +PartInfo::PartInfo() { - } PartInfo::PartInfo(IPresentablePart::Pointer part) { this->Set(part); } void PartInfo::Set(IPresentablePart::Pointer part) { name = part->GetName(); title = part->GetTitle(); contentDescription = part->GetTitleStatus(); - image = static_cast (part->GetTitleImage()); + image = part->GetTitleImage(); toolTip = part->GetTitleToolTip(); dirty = part->IsDirty(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.h index 8e297f5a4e..15adb7070e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPartInfo.h @@ -1,44 +1,44 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPARTINFO_H_ #define BERRYPARTINFO_H_ #include #include namespace berry { struct PartInfo { QString name; QString title; QString contentDescription; QString toolTip; - QIcon* image; + QIcon image; bool dirty; PartInfo(); PartInfo(IPresentablePart::Pointer part); void Set(IPresentablePart::Pointer part); }; } #endif /* BERRYPARTINFO_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIIntroPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIIntroPart.h index 6b40b4c98e..3a1f81012d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIIntroPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIIntroPart.h @@ -1,213 +1,213 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIINTROPART_H_ #define BERRYIINTROPART_H_ #include #include #include #include #include #include "berryIIntroSite.h" #include namespace berry { /** * The intro part is a visual component within the workbench responsible for * introducing the product to new users. The intro part is typically shown the * first time a product is started up. *

* The intro part implementation is contributed to the workbench via the * org.blueberry.ui.intro extension point. There can be several * intro part implementations, and associations between intro part * implementations and products. The workbench will only make use of the intro * part implementation for the current product (as given by * {@link berry::Platform#GetProduct()}. There is at most one * intro part instance in the entire workbench, and it resides in exactly one * workbench window at a time. *

*

* This interface in not intended to be directly implemented. Rather, clients * providing a intro part implementation should subclass * {@link berry::IntroPart}. *

* * @see IIntroManager#ShowIntro(IWorkbenchWindow::Pointer, bool) * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IIntroPart : public virtual Object { // IAdaptable { berryObjectMacro(berry::IIntroPart) ~IIntroPart(); /** * The property id for getTitleImage and * getTitle. * * @since 3.2 this property now covers changes to getTitle in * addition to getTitleImage */ //static const int PROP_TITLE = IWorkbenchPart::PROP_TITLE; /** * Returns the site for this intro part. * * @return the intro site */ virtual IIntroSite::Pointer GetIntroSite() const = 0; /** * Initializes this intro part with the given intro site. A memento is * passed to the part which contains a snapshot of the part state from a * previous session. Where possible, the part should try to recreate that * state. *

* This method is automatically called by the workbench shortly after * part construction. It marks the start of the intro's lifecycle. Clients * must not call this method. *

* * @param site the intro site * @param memento the intro part state or null if there is no previous * saved state * @exception PartInitException if this part was not initialized * successfully */ virtual void Init(IIntroSite::Pointer site, IMemento::Pointer memento) = 0; /** * Sets the standby state of this intro part. An intro part should render * itself differently in the full and standby modes. In standby mode, the * part should be partially visible to the user but otherwise allow them * to work. In full mode, the part should be fully visible and be the center * of the user's attention. *

* This method is automatically called by the workbench at appropriate * times. Clients must not call this method directly (call * {@link IIntroManager#setIntroStandby(IIntroPart, boolean)} instead. *

* * @param standby true to put this part in its partially * visible standy mode, and false to make it fully visible */ virtual void StandbyStateChanged(bool standby) = 0; /** * Saves the object state within a memento. *

* This method is automatically called by the workbench at appropriate * times. Clients must not call this method directly. *

* * @param memento a memento to receive the object state */ virtual void SaveState(IMemento::Pointer memento) = 0; /** * Adds a listener for changes to properties of this intro part. * Has no effect if an identical listener is already registered. *

* The properties ids are as follows: *

    *
  • IIntroPart.PROP_TITLE
  • *
*

* * @param listener a property listener */ virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; /** * Creates the SWT controls for this intro part. *

* Clients should not call this method (the workbench calls this method when * it needs to, which may be never). *

*

* For implementors this is a multi-step process: *

    *
  1. Create one or more controls within the parent.
  2. *
  3. Set the parent layout as needed.
  4. *
  5. Register any global actions with the IActionService.
  6. *
  7. Register any popup menus with the IActionService.
  8. *
  9. Register a selection provider with the ISelectionService * (optional).
  10. *
*

* * @param parent the parent control */ virtual void CreatePartControl(void* parent) = 0; /** * Returns the title image of this intro part. If this value changes * the part must fire a property listener event with * {@link IIntroPart#PROP_TITLE}. *

* The title image is usually used to populate the title bar of this part's * visual container. Since this image is managed by the part itself, callers * must not dispose the returned image. *

* * @return the title image */ - virtual void* GetTitleImage() const = 0; + virtual QIcon GetTitleImage() const = 0; /** * Returns the title of this intro part. If this value changes * the part must fire a property listener event with * {@link IIntroPart#PROP_TITLE}. *

* The title is used to populate the title bar of this part's visual * container. *

* * @return the intro part title (not null) */ virtual QString GetPartName() const = 0; /** * Removes the given property listener from this intro part. * Has no affect if an identical listener is not registered. * * @param listener a property listener */ virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; /** * Asks this part to take focus within the workbench. *

* Clients should not call this method (the workbench calls this method at * appropriate times). To have the workbench activate a part, use * {@link IIntroManager#showIntro(IWorkbenchWindow, boolean)}. *

*/ virtual void SetFocus() = 0; }; } Q_DECLARE_INTERFACE(berry::IIntroPart, "org.blueberry.ui.IIntroPart") #endif /* BERRYIINTROPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.cpp index 45f36ac759..332989c1c3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.cpp @@ -1,190 +1,184 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIntroPart.h" #include #include #include #include #include #include "util/berrySafeRunnable.h" #include "internal/berryWorkbenchRegistryConstants.h" namespace berry { class PropChangedRunnable: public SafeRunnable { public: berryObjectMacro(PropChangedRunnable) IPropertyChangeListener::Events::EventType::AbstractDelegate* delegate; PropChangedRunnable(PropertyChangeEvent::Pointer event) : event(event) { } void Run() { delegate->Execute(event); } private: PropertyChangeEvent::Pointer event; }; QString IntroPart::GetDefaultTitle() const { return "Welcome"; } void IntroPart::FirePropertyChange(int propertyId) { ObjectInt::Pointer val(new ObjectInt(propertyId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = propChangeEvents.propertyChange.GetListeners(); for (ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } IConfigurationElement::Pointer IntroPart::GetConfigurationElement() { return configElement; } -void* IntroPart::GetDefaultImage() const +QIcon IntroPart::GetDefaultImage() const { - return 0; + return QIcon(); } void IntroPart::SetSite(IIntroSite::Pointer site) { this->partSite = site; } -void IntroPart::SetTitleImage(void* titleImage) +void IntroPart::SetTitleImage(const QIcon& titleImage) { //Do not send changes if they are the same - if (this->titleImage == titleImage) + if (this->imageDescriptor.cacheKey() == titleImage.cacheKey()) { return; } - this->titleImage = titleImage; + this->imageDescriptor = titleImage; FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void IntroPart::SetTitle(const QString& titleLabel) { if (this->titleLabel == titleLabel) return; this->titleLabel = titleLabel; FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void IntroPart::AddPropertyListener(IPropertyChangeListener *l) { propChangeEvents.AddListener(l); } IntroPart::~IntroPart() { } IIntroSite::Pointer IntroPart::GetIntroSite() const { return partSite; } -void* IntroPart::GetTitleImage() const +QIcon IntroPart::GetTitleImage() const { - if (titleImage != 0) + if (!this->imageDescriptor.isNull()) { - return titleImage; + return this->imageDescriptor; } return GetDefaultImage(); } QString IntroPart::GetPartName() const { if (!titleLabel.isEmpty()) { return titleLabel; } return GetDefaultTitle(); } void IntroPart::Init(IIntroSite::Pointer site, IMemento::Pointer /*memento*/) throw (PartInitException) { SetSite(site); } void IntroPart::RemovePropertyListener(IPropertyChangeListener *l) { propChangeEvents.RemoveListener(l); } void IntroPart::SaveState(IMemento::Pointer /*memento*/) { //no-op } void IntroPart::SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& /*propertyName*/, const Object::Pointer& /*data*/) { // Save config element. configElement = cfig; titleLabel = cfig->GetAttribute(WorkbenchRegistryConstants::ATT_LABEL); // Icon. QString strIcon = cfig->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); if (strIcon.isEmpty()) { return; } imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configElement->GetContributor()->GetName(), strIcon); - if (!imageDescriptor) - { - return; - } - - titleImage = imageDescriptor->CreateImage(true); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.h index e67325a3a5..f395a6e61e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/intro/berryIntroPart.h @@ -1,225 +1,224 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYINTROPART_H_ #define BERRYINTROPART_H_ #include "berryIIntroPart.h" #include "berryIIntroSite.h" #include -#include #include #include +#include + namespace berry { /** * Abstract base implementation of an intro part. *

* Subclasses must implement the following methods: *

    *
  • CreatePartControl- to create the intro part's controls *
  • *
  • SetFocus- to accept focus
  • *
  • StandbyStateChanged- to change the standby mode
  • *
*

*

* Subclasses may extend or reimplement the following methods as required: *

    *
  • SetInitializationData- extend to provide additional * initialization when the intro extension is instantiated
  • *
  • Init(IIntroSite::Pointer, IMemento::Pointer)- extend to provide additional * initialization when intro is assigned its site
  • *
  • GetAdapter- reimplement to make their intro adaptable *
  • *
*

*/ class BERRY_UI_QT IntroPart: public QObject, public IIntroPart, public IExecutableExtension { Q_OBJECT - Q_INTERFACES(berry::IIntroPart berry::IExecutableExtension); + Q_INTERFACES(berry::IIntroPart berry::IExecutableExtension) private: IConfigurationElement::Pointer configElement; - ImageDescriptor::Pointer imageDescriptor; + QIcon imageDescriptor; IIntroSite::Pointer partSite; - void* titleImage; - QString titleLabel; IPropertyChangeListener::Events propChangeEvents; /** * Return the default title string. * * @return the default title string */ QString GetDefaultTitle() const; protected: /** * Fires a property changed event. * * @param propertyId * the id of the property that changed */ void FirePropertyChange(int propertyId); /** * Returns the configuration element for this part. The configuration * element comes from the plug-in registry entry for the extension defining * this part. * * @return the configuration element for this part */ IConfigurationElement::Pointer GetConfigurationElement(); /** * Returns the default title image. * * @return the default image */ - void* GetDefaultImage() const; + QIcon GetDefaultImage() const; /** * Sets the part site. *

* Subclasses must invoke this method from {@link org.eclipse.ui.intro.IIntroPart#init(IIntroSite, IMemento)}. *

* * @param site the intro part site */ void SetSite(IIntroSite::Pointer site); /** * Sets or clears the title image of this part. * * @param titleImage * the title image, or null to clear */ - void SetTitleImage(void* titleImage); + void SetTitleImage(const QIcon& titleImage); /** * Set the title string for this part. * * @param titleLabel the title string. Must not be null. * @since 3.2 */ void SetTitle(const QString& titleLabel); public: /* (non-Javadoc) * @see org.eclipse.ui.intro.IIntroPart#addPropertyListener(org.eclipse.ui.IPropertyListener) */ void AddPropertyListener(IPropertyChangeListener* l); /** * The IntroPart implementation of this * IIntroPart method disposes the title image loaded by * setInitializationData. Subclasses may extend. */ ~IntroPart(); /** * This implementation of the method declared by IAdaptable * passes the request along to the platform's adapter manager; roughly * Platform.getAdapterManager().getAdapter(this, adapter). * Subclasses may override this method (however, if they do so, they should * invoke the method on their superclass to ensure that the Platform's * adapter manager is consulted). */ // Object getAdapter(Class adapter) { // return Platform.getAdapterManager().getAdapter(this, adapter); // } /* * (non-Javadoc) * * @see org.eclipse.ui.intro.IIntroPart#getIntroSite() */ IIntroSite::Pointer GetIntroSite() const; /* (non-Javadoc) * @see org.eclipse.ui.intro.IIntroPart#getTitleImage() */ - void* GetTitleImage() const; + QIcon GetTitleImage() const; /* (non-Javadoc) * @see org.eclipse.ui.intro.IIntroPart#getTitle() */ QString GetPartName() const; /** * The base implementation of this {@link org.eclipse.ui.intro.IIntroPart}method ignores the * memento and initializes the part in a fresh state. Subclasses may extend * to perform any state restoration, but must call the super method. * * @param site * the intro site * @param memento * the intro part state or null if there is no * previous saved state * @exception PartInitException * if this part was not initialized successfully */ void Init(IIntroSite::Pointer site, IMemento::Pointer memento) throw (PartInitException); /* (non-Javadoc) * @see org.eclipse.ui.intro.IIntroPart#removePropertyListener(org.eclipse.ui.IPropertyListener) */ void RemovePropertyListener(IPropertyChangeListener* l); /** * The base implementation of this {@link org.eclipse.ui.intro.IIntroPart} method does nothing. * Subclasses may override. * * @param memento * a memento to receive the object state */ void SaveState(IMemento::Pointer memento); /** * The IntroPart implementation of this * IExecutableExtension records the configuration element in * and internal state variable (accessible via getConfigElement). * It also loads the title image, if one is specified in the configuration * element. Subclasses may extend. * * Should not be called by clients. It is called by the core plugin when * creating this executable extension. */ void SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& propertyName, const Object::Pointer& data); }; } #endif /* BERRYINTROPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h index c96c21b17d..e645b9a28f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h @@ -1,269 +1,269 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPRESENTABLEPART_H_ #define BERRYIPRESENTABLEPART_H_ #include #include "berryISizeProvider.h" #include "berryRectangle.h" #include "berryIPropertyChangeListener.h" namespace berry { /** * This is a skin's interface to the contents of a view or editor. Note that this * is essentially the same as IWorkbenchPart, except it does not provide access * to lifecycle events and allows repositioning of the part. * * Not intended to be implemented by clients. * * @since 3.0 * @since 3.4 now extends {@link org.blueberry.ui.ISizeProvider} * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPresentablePart : public Object, public ISizeProvider { berryObjectMacro(berry::IPresentablePart) ~IPresentablePart(); /** * The property id for isDirty. */ static const int PROP_DIRTY; // = IWorkbenchPartConstants.PROP_DIRTY; /** * The property id for getEditorInput. */ static const int PROP_INPUT; // = IWorkbenchPartConstants.PROP_INPUT; /** * The property id for getTitle, getTitleImage * and getTitleToolTip. */ static const int PROP_TITLE; // = IWorkbenchPartConstants.PROP_TITLE; /** * The property id for IWorkbenchPart2.getContentDescription() */ static const int PROP_CONTENT_DESCRIPTION; // = IWorkbenchPartConstants.PROP_CONTENT_DESCRIPTION; /** * The property id for IWorkbenchPart2.getContentDescription() */ static const int PROP_PART_NAME; // = IWorkbenchPartConstants.PROP_PART_NAME; /** * The property id for isBusy. */ static const int PROP_BUSY; // = 0x92; /** * The property id for toolbar changes */ static const int PROP_TOOLBAR; // = 0x93; /** * The property id for highlighting the * part if it is not in front. */ static const int PROP_HIGHLIGHT_IF_BACK; // = 0x94; /** * The property id for pane menu changes */ static const int PROP_PANE_MENU; // = 0x302; /** * The property id for preferred size changes * @since 3.4 */ static const int PROP_PREFERRED_SIZE; // = IWorkbenchPartConstants.PROP_PREFERRED_SIZE; /** * Sets the bounds of this part. * * @param bounds bounding rectangle (not null) */ virtual void SetBounds(const Rectangle& bounds) = 0; /** * Notifies the part whether or not it is visible in the current * perspective. A part is visible iff any part of its widgetry can * be seen. * * @param isVisible true if the part has just become visible, false * if the part has just become hidden */ virtual void SetVisible(bool isVisible) = 0; /** * Forces this part to have focus. */ virtual void SetFocus() = 0; /** * Adds a listener for changes to properties of this workbench part. * Has no effect if an identical listener is already registered. *

* The properties ids are defined by the PROP_* constants, above. *

* * @param listener a property listener (not null) */ virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; /** * Remove a listener that was previously added using addPropertyListener. * * @param listener a property listener (not null) */ virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; /** * Returns the short name of the part. This is used as the text on * the tab when this part is stacked on top of other parts. * * @return the short name of the part (not null) */ virtual QString GetName() const = 0; /** * Returns the title of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

* The title is used to populate the title bar of this part's visual * container. *

* * @return the workbench part title (not null) */ virtual QString GetTitle() const = 0; /** * Returns the status message from the part's title, or the empty string if none. * This is a substring of the part's title. A typical title will consist of * the part name, a separator, and a status message describing the current contents. *

* Presentations can query getName() and getTitleStatus() if they want to display * the status message and name separately, or they can use getTitle() if they want * to display the entire title. *

* * @return the status message or the empty string if none (not null) */ virtual QString GetTitleStatus() const = 0; /** * Returns the title image of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

* The title image is usually used to populate the title bar of this part's * visual container. Since this image is managed by the part itself, callers * must not dispose the returned image. *

* * @return the title image */ - virtual void* GetTitleImage() = 0; + virtual QIcon GetTitleImage() = 0; /** * Returns the title tool tip text of this workbench part. If this value * changes the part must fire a property listener event with * PROP_TITLE. *

* The tool tip text is used to populate the title bar of this part's * visual container. *

* * @return the workbench part title tool tip (not null) */ virtual QString GetTitleToolTip() const = 0; /** * Returns true iff the contents of this part have changed recently. For * editors, this indicates that the part has changed since the last save. * For views, this indicates that the view contains interesting changes * that it wants to draw the user's attention to. * * @return true iff the part is dirty */ virtual bool IsDirty() const = 0; /** * Return true if the the receiver is currently in a busy state. * @return boolean true if busy */ virtual bool IsBusy() const = 0; /** * Returns true iff this part can be closed * * @return true iff this part can be closed * @since 3.1 */ virtual bool IsCloseable() const = 0; /** * Returns the local toolbar for this part, or null if this part does not * have a local toolbar. Callers must not dispose or downcast the return value. * * @return the local toolbar for the part, or null if none */ virtual void* GetToolBar() = 0; /** * Returns the menu for this part or null if none * * @return the menu for this part or null if none */ //virtual IPartMenu getMenu(); /** * Returns an SWT control that can be used to indicate the tab order for * this part. This can be returned as part of the result to * {@link StackPresentation#getTabList(IPresentablePart)}. Any other use of this control is * unsupported. This may return a placeholder control that is only * meaningful in the context of getTabList. * * @return the part's control (not null) */ virtual void* GetControl() = 0; /** * Get a property from the part's arbitrary property set. *

* Note: this is a different set of properties than the ones covered * by the PROP_* constants. *

* * @param key * The property key to retrieve. Must not be null. * @return the property, or null if that property is not set. * @since 3.3 */ virtual QString GetPartProperty(const QString& key) const = 0; }; } #endif /* BERRYIPRESENTABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.cpp deleted file mode 100755 index 356450c8f7..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "berryImageTweaklet.h" - -namespace berry -{ - -Tweaklets::TweakKey ImageTweaklet::KEY = - Tweaklets::TweakKey(); - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.h deleted file mode 100755 index 553911d180..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryImageTweaklet.h +++ /dev/null @@ -1,50 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef BERRYIMAGETWEAKLET_H_ -#define BERRYIMAGETWEAKLET_H_ - -#include "internal/berryTweaklets.h" - -#include - -#include "berryImageDescriptor.h" - -#include - -namespace berry -{ - -/** - * Provides the set of cursors used for drag-and-drop. - */ -struct BERRY_UI_QT ImageTweaklet -{ - static Tweaklets::TweakKey KEY; - - virtual SmartPointer CreateFromFile(const QString& filename, const QString& pluginid) = 0; - virtual SmartPointer CreateFromImage(void* img) = 0; - virtual SmartPointer GetMissingImageDescriptor() = 0; - - virtual void DestroyImage(const void* img) = 0; -}; - -} - -Q_DECLARE_INTERFACE(berry::ImageTweaklet, "org.blueberry.ImageTweaklet") - -#endif /* BERRYIMAGETWEAKLET_H_ */ diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp index 54b01ebd90..e593e36dd1 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp @@ -1,785 +1,785 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //Qmitk headers #include "QmitkViewNavigatorWidget.h" // Blueberry #include #include #include #include #include #include #include // Qt #include #include #include #include #include class KeywordRegistry { public: KeywordRegistry() { berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords"); for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); QString keywordLabels = (*keywordExtsIt)->GetAttribute("label"); m_Keywords[keywordId].push_back(keywordLabels); } } QStringList GetKeywords(const QString& id) { return m_Keywords[id]; } QStringList GetKeywords(const QStringList& ids) { QStringList result; for (int i = 0; i < ids.size(); ++i) { result.append(this->GetKeywords(ids[i])); } return result; } private: QHash m_Keywords; }; class ClassFilterProxyModel : public QSortFilterProxyModel { private : bool hasToBeDisplayed(const QModelIndex index) const; bool displayElement(const QModelIndex index) const; public: ClassFilterProxyModel(QObject *parent = NULL); bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; ClassFilterProxyModel::ClassFilterProxyModel(QObject *parent): QSortFilterProxyModel(parent) { } bool ClassFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return hasToBeDisplayed(index); } bool ClassFilterProxyModel::displayElement(const QModelIndex index) const { bool result = false; QString type = sourceModel()->data(index, Qt::DisplayRole).toString(); QStandardItem * item = dynamic_cast(sourceModel())->itemFromIndex(index); if (type.contains(filterRegExp())) { return true; } { mitk::QtViewItem* viewItem = dynamic_cast(item); if (viewItem) { for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } { mitk::QtPerspectiveItem* viewItem = dynamic_cast(item); if (viewItem) { for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } return result; } bool ClassFilterProxyModel::hasToBeDisplayed(const QModelIndex index) const { bool result = false; if ( sourceModel()->rowCount(index) > 0 ) { for( int ii = 0; ii < sourceModel()->rowCount(index); ii++) { QModelIndex childIndex = sourceModel()->index(ii,0,index); if ( ! childIndex.isValid() ) break; result = hasToBeDisplayed(childIndex); result |= displayElement(index); if (result) { break; } } } else { result = displayElement(index); } return result; } class ViewNavigatorPerspectiveListener: public berry::IPerspectiveListener { public: ViewNavigatorPerspectiveListener(QmitkViewNavigatorWidget* p) : parentWidget(p) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED | Events::PART_CHANGED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) { } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } using IPerspectiveListener::PerspectiveChanged; void PerspectiveChanged(const berry::IWorkbenchPage::Pointer&, const berry::IPerspectiveDescriptor::Pointer&, const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId) { if (changeId=="viewHide" && partRef->GetId()=="org.mitk.views.viewnavigatorview") berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(parentWidget->m_PerspectiveListener.data()); else parentWidget->UpdateTreeList(NULL, partRef.GetPointer(), changeId); } private: QmitkViewNavigatorWidget* parentWidget; }; struct ViewNavigatorWindowListener : public berry::IWindowListener { ViewNavigatorWindowListener(QmitkViewNavigatorWidget* switcher) : switcher(switcher) , m_Done(false) {} virtual void WindowOpened(const berry::IWorkbenchWindow::Pointer& window) { if (m_Done) return; if ( switcher->FillTreeList() ) { m_Done = true; switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); } } virtual void WindowActivated(const berry::IWorkbenchWindow::Pointer& window) { if (m_Done) return; if ( switcher->FillTreeList() ) { m_Done = true; switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); } } private: QmitkViewNavigatorWidget* switcher; bool m_Done; }; bool compareViews(const berry::IViewDescriptor::Pointer& a, const berry::IViewDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) return false; return a->GetLabel().compare(b->GetLabel()) < 0; } bool comparePerspectives(const berry::IPerspectiveDescriptor::Pointer& a, const berry::IPerspectiveDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) return false; return a->GetLabel().compare(b->GetLabel()) < 0; } bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b) { if (a==NULL || b==NULL) return false; return a->text().compare(b->text()) < 0; } QmitkViewNavigatorWidget::QmitkViewNavigatorWidget( QWidget * parent, Qt::WindowFlags ) : QWidget(parent) { m_Generated = false; this->CreateQtPartControl(this); } QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget() { } void QmitkViewNavigatorWidget::setFocus() { m_Controls.lineEdit->setFocus(); } void QmitkViewNavigatorWidget::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNotNull()) { m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->AddPerspectiveListener(m_PerspectiveListener.data()); } else { m_WindowListener.reset(new ViewNavigatorWindowListener(this)); berry::PlatformUI::GetWorkbench()->AddWindowListener(m_WindowListener.data()); } m_Parent = parent; m_Controls.setupUi( parent ); connect( m_Controls.m_PluginTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(CustomMenuRequested(QPoint))); connect( m_Controls.m_PluginTreeView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(ItemClicked(const QModelIndex&))); connect( m_Controls.lineEdit, SIGNAL(textChanged(QString)), SLOT(FilterChanged())); m_ContextMenu = new QMenu(m_Controls.m_PluginTreeView); m_Controls.m_PluginTreeView->setContextMenuPolicy(Qt::CustomContextMenu); // Create a new TreeModel for the data m_TreeModel = new QStandardItemModel(); m_FilterProxyModel = new ClassFilterProxyModel(this); m_FilterProxyModel->setSourceModel(m_TreeModel); //proxyModel->setFilterFixedString("Diff"); m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel); } void QmitkViewNavigatorWidget::UpdateTreeList(QStandardItem* root, berry::IWorkbenchPartReference *partRef, const std::string &changeId) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNull()) return; if( !m_Generated ) { m_Generated = FillTreeList(); } if (root==NULL) root = m_TreeModel->invisibleRootItem(); for (int i=0; irowCount(); i++) { QStandardItem* item = root->child(i); QFont font; if (dynamic_cast(item)) { mitk::QtPerspectiveItem* pItem = dynamic_cast(item); berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); if (currentPersp.IsNotNull() && currentPersp->GetId()==pItem->m_Perspective->GetId()) font.setBold(true); pItem->setFont(font); } mitk::QtViewItem* vItem = dynamic_cast(item); if (vItem) { QList viewParts(page->GetViews()); for (int i=0; iGetPartName()==vItem->m_View->GetLabel()) { font.setBold(true); break; } if( partRef!=NULL && partRef->GetId()==vItem->m_View->GetId() && changeId=="viewHide") font.setBold(false); vItem->setFont(font); } UpdateTreeList(item, partRef, changeId); } } bool QmitkViewNavigatorWidget::FillTreeList() { // active workbench window available? if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNull()) return false; // active page available? berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNull()) return false; // everything is fine and we can remove the window listener if (m_WindowListener != nullptr) berry::PlatformUI::GetWorkbench()->RemoveWindowListener(m_WindowListener.data()); // initialize tree model m_TreeModel->clear(); QStandardItem *treeRootItem = m_TreeModel->invisibleRootItem(); // get all available perspectives berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); QList perspectiveDescriptors(perspRegistry->GetPerspectives()); qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); // get all Keywords KeywordRegistry keywordRegistry; berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); QStringList perspectiveExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetPerspectiveExcludeList(); std::vector< QStandardItem* > categoryItems; QStandardItem *perspectiveRootItem = new QStandardItem("Workflows"); perspectiveRootItem->setEditable(false); perspectiveRootItem->setFont(QFont("", 12, QFont::Normal)); treeRootItem->appendRow(perspectiveRootItem); for (int i=0; iGetId()) { skipPerspective = true; break; } if (skipPerspective) continue; //QIcon* pIcon = static_cast(p->GetImageDescriptor()->CreateImage()); mitk::QtPerspectiveItem* pItem = new mitk::QtPerspectiveItem(p->GetLabel()); pItem->m_Perspective = p; pItem->m_Description = p->GetDescription(); QStringList keylist = p->GetKeywordReferences(); pItem->m_Tags = keywordRegistry.GetKeywords(keylist); pItem->setEditable(false); QFont font; font.setBold(true); if (currentPersp.IsNotNull() && currentPersp->GetId()==p->GetId()) pItem->setFont(font); QStringList catPath = p->GetCategoryPath(); if (catPath.isEmpty()) { perspectiveRootItem->appendRow(pItem); } else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext() == catPath.front()) { categoryItem = categoryItems.at(c); break; } } if (categoryItem==NULL) { categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(pItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); // get all available views berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); QList viewDescriptors(viewRegistry->GetViews()); QList viewParts(page->GetViews()); qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); QStandardItem* emptyItem = new QStandardItem(); emptyItem->setFlags(Qt::ItemIsEnabled); treeRootItem->appendRow(emptyItem); QStringList viewExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetViewExcludeList(); QStandardItem* viewRootItem = new QStandardItem(QIcon(),"Views"); viewRootItem->setFont(QFont("", 12, QFont::Normal)); viewRootItem->setEditable(false); treeRootItem->appendRow(viewRootItem); categoryItems.clear(); QStandardItem* noCategoryItem = new QStandardItem(QIcon(),"Miscellaneous"); noCategoryItem->setEditable(false); noCategoryItem->setFont(QFont("", 12, QFont::Normal)); for (int i = 0; i < viewDescriptors.size(); ++i) { berry::IViewDescriptor::Pointer v = viewDescriptors[i]; bool skipView = false; for(int e=0; eGetId()) { skipView = true; break; } if (skipView) continue; QStringList catPath = v->GetCategoryPath(); - QIcon* icon = static_cast(v->GetImageDescriptor()->CreateImage()); - mitk::QtViewItem* vItem = new mitk::QtViewItem(*icon, v->GetLabel()); + QIcon icon = v->GetImageDescriptor(); + mitk::QtViewItem* vItem = new mitk::QtViewItem(icon, v->GetLabel()); vItem->m_View = v; vItem->setToolTip(v->GetDescription()); vItem->m_Description = v->GetDescription(); QStringList keylist = v->GetKeywordReferences(); vItem->m_Tags = keywordRegistry.GetKeywords(keylist); vItem->setEditable(false); for (int i=0; iGetPartName()==v->GetLabel()) { QFont font; font.setBold(true); vItem->setFont(font); break; } if (catPath.empty()) noCategoryItem->appendRow(vItem); else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext() == catPath.front()) { categoryItem = categoryItems.at(c); break; } if (categoryItem==NULL) { categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(vItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); if (noCategoryItem->hasChildren()) viewRootItem->appendRow(noCategoryItem); m_Controls.m_PluginTreeView->expandAll(); return true; } void QmitkViewNavigatorWidget::FilterChanged() { QString filterString = m_Controls.lineEdit->text(); // if (filterString.size() > 0 ) m_Controls.m_PluginTreeView->expandAll(); // else // m_Controls.m_PluginTreeView->collapseAll(); // QRegExp::PatternSyntax syntax = QRegExp::RegExp; Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; QString strPattern = "^*" + filterString; QRegExp regExp(strPattern, caseSensitivity); m_FilterProxyModel->setFilterRegExp(regExp); } void QmitkViewNavigatorWidget::ItemClicked(const QModelIndex &index) { QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if ( dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { try { mitk::QtPerspectiveItem* pItem = dynamic_cast< mitk::QtPerspectiveItem* >(item); berry::PlatformUI::GetWorkbench()->ShowPerspective( pItem->m_Perspective->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } catch (...) { QMessageBox::critical(0, "Opening Perspective Failed", QString("The requested perspective could not be opened.\nSee the log for details.")); } } else if ( dynamic_cast< mitk::QtViewItem* >(item) ) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { try { mitk::QtViewItem* vItem = dynamic_cast< mitk::QtViewItem* >(item); page->ShowView(vItem->m_View->GetId()); } catch (berry::PartInitException e) { BERRY_ERROR << "Error: " << e.what() << std::endl; } } } } void QmitkViewNavigatorWidget::AddPerspective() { QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); try { berry::IPerspectiveDescriptor::Pointer perspDesc; perspDesc = perspRegistry->CreatePerspective(dialog->GetPerspectiveName(), perspRegistry->FindPerspectiveWithId(perspRegistry->GetDefaultPerspective())); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); } catch(...) { QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); } FillTreeList(); } void QmitkViewNavigatorWidget::ClonePerspective() { if (m_RegisteredPerspective.IsNotNull()) { QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); QString defaultName = m_RegisteredPerspective->GetLabel(); defaultName.append(" Copy"); dialog->SetPerspectiveName(defaultName); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); try { berry::IPerspectiveDescriptor::Pointer perspDesc = perspRegistry->ClonePerspective(dialog->GetPerspectiveName(), dialog->GetPerspectiveName(), m_RegisteredPerspective); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); } catch(...) { QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); } FillTreeList(); } } void QmitkViewNavigatorWidget::ResetPerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to reset the current perspective?", QMessageBox::Yes|QMessageBox::No).exec()) berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkViewNavigatorWidget::DeletePerspective() { if (m_RegisteredPerspective.IsNotNull()) { QString question = "Do you really want to remove the perspective '"; question.append(m_RegisteredPerspective->GetLabel()); question.append("'?"); if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", question, QMessageBox::Yes|QMessageBox::No).exec()) { if( m_RegisteredPerspective == berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective() ) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->CloseCurrentPerspective(true, true); } berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); perspRegistry->DeletePerspective(m_RegisteredPerspective); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->RemovePerspective(m_RegisteredPerspective); FillTreeList(); if (! berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective()) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->Close(); } } } } void QmitkViewNavigatorWidget::ClosePerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close the current perspective?", QMessageBox::Yes|QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->CloseCurrentPerspective(true, true); // if ( page->GetPerspective().IsNull() ) // { // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); // } } } void QmitkViewNavigatorWidget::CloseAllPerspectives() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close all perspectives?", QMessageBox::Yes|QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->CloseAllPerspectives(true, true); // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } } void QmitkViewNavigatorWidget::ExpandAll() { m_Controls.m_PluginTreeView->expandAll(); } void QmitkViewNavigatorWidget::CollapseAll() { m_Controls.m_PluginTreeView->collapseAll(); } void QmitkViewNavigatorWidget::CustomMenuRequested(QPoint pos) { QModelIndex index = m_Controls.m_PluginTreeView->indexAt(pos); QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if (m_ContextMenu==NULL) return; m_ContextMenu->clear(); m_RegisteredPerspective = NULL; QAction* expandAction = new QAction("Expand tree", this); m_ContextMenu->addAction(expandAction); connect(expandAction, SIGNAL(triggered()), SLOT(ExpandAll())); QAction* collapseAction = new QAction("Collapse tree", this); m_ContextMenu->addAction(collapseAction); connect(collapseAction, SIGNAL(triggered()), SLOT(CollapseAll())); m_ContextMenu->addSeparator(); if ( item!=NULL && dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { m_RegisteredPerspective = dynamic_cast< mitk::QtPerspectiveItem* >(item)->m_Perspective; //m_ContextMenu->addSeparator(); QAction* cloneAction = new QAction("Duplicate perspective", this); m_ContextMenu->addAction(cloneAction); connect(cloneAction, SIGNAL(triggered()), SLOT(ClonePerspective())); if (!m_RegisteredPerspective->IsPredefined()) { QAction* deleteAction = new QAction("Remove perspective", this); m_ContextMenu->addAction(deleteAction); connect(deleteAction, SIGNAL(triggered()), SLOT(DeletePerspective())); } m_ContextMenu->addSeparator(); } QAction* resetAction = new QAction("Reset current perspective", this); m_ContextMenu->addAction(resetAction); connect(resetAction, SIGNAL(triggered()), SLOT(ResetPerspective())); QAction* closeAction = new QAction("Close current perspective", this); m_ContextMenu->addAction(closeAction); connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective())); m_ContextMenu->addSeparator(); QAction* closeAllAction = new QAction("Close all perspectives", this); m_ContextMenu->addAction(closeAllAction); connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives())); m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos)); }