diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake index 21ce7aebab..8d56f4963a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake @@ -1,453 +1,447 @@ 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 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/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 berryQtGlobalEventFilter.cpp berryQtMainWindowControl.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/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/application/berryIWorkbenchWindowConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h index 933e1c1753..b53be8964a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h @@ -1,378 +1,376 @@ /*=================================================================== 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 BERRYIWORKBENCHWINDOWCONFIGURER_H_ #define BERRYIWORKBENCHWINDOWCONFIGURER_H_ #include #include -#include "berryPoint.h" - class QMenuBar; namespace berry { struct IActionBarConfigurer; struct IDropTargetListener; struct IMemento; struct IWorkbenchConfigurer; struct IWorkbenchWindow; /** * Interface providing special access for configuring workbench windows. *

* %Window configurer objects are in 1-1 correspondence with the workbench * windows they configure. Clients may use Get/SetData to * associate arbitrary state with the window configurer object. *

*

* Note that these objects are only available to the main application * (the plug-in that creates and owns the workbench). *

*

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

* * @see IWorkbenchConfigurer#GetWindowConfigurer() * @see WorkbenchAdvisor#PreWindowOpen() * @note This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IWorkbenchWindowConfigurer : public Object { berryObjectMacro(berry::IWorkbenchWindowConfigurer) ~IWorkbenchWindowConfigurer(); /** * Returns the underlying workbench window. * * @return the workbench window */ virtual SmartPointer GetWindow() = 0; /** * Returns the workbench configurer. * * @return the workbench configurer */ virtual SmartPointer GetWorkbenchConfigurer() = 0; /** * Returns the action bar configurer for this workbench * window. * * @return the action bar configurer */ virtual SmartPointer GetActionBarConfigurer() = 0; /** * Returns the title of the underlying workbench window. * * @return the window title */ virtual QString GetTitle() = 0; /** * Sets the title of the underlying workbench window. * * @param title the window title */ virtual void SetTitle(const QString& title) = 0; /** * Returns whether the underlying workbench window has a menu bar. *

* The initial value is true. *

* * @return true for a menu bar, and false * for no menu bar */ virtual bool GetShowMenuBar() const = 0; /** * Sets whether the underlying workbench window has a menu bar. * * @param show true for a menu bar, and false * for no menu bar */ virtual void SetShowMenuBar(bool show) = 0; /** * Returns whether the underlying workbench window has a tool bar. *

* The initial value is true. *

* * @return true for a tool bar, and false * for no tool bar */ virtual bool GetShowToolBar() const = 0; /** * Sets whether the underlying workbench window has a tool bar. * * @param show true for a tool bar, and false * for no tool bar */ virtual void SetShowToolBar(bool show) = 0; /** * Returns whether the underlying workbench window has a status line. *

* The initial value is true. *

* * @return true for a status line, and false * for no status line */ virtual bool GetShowStatusLine() const = 0; /** * Sets whether the underlying workbench window has a status line. * * @param show true for a status line, and false * for no status line */ virtual void SetShowStatusLine(bool show) = 0; /** * Returns whether the underlying workbench window has a perspective bar (the * perspective bar provides buttons to quickly switch between perspectives). *

* The initial value is false. *

* * @return true for a perspective bar, and false * for no perspective bar */ virtual bool GetShowPerspectiveBar() const = 0; /** * Sets whether the underlying workbench window has a perspective bar (the * perspective bar provides buttons to quickly switch between perspectives). * * @param show true for a perspective bar, and * false for no perspective bar */ virtual void SetShowPerspectiveBar(bool show) = 0; /** * Returns whether the underlying workbench window has a progress indicator. *

* The initial value is false. *

* * @return true for a progress indicator, and false * for no progress indicator */ virtual bool GetShowProgressIndicator() const = 0; /** * Sets whether the underlying workbench window has a progress indicator. * * @param show true for a progress indicator, and false * for no progress indicator */ virtual void SetShowProgressIndicator(bool show) = 0; /** * Returns the style bits to use for the window's main widget when it is created. * The default is 0. * * @return the style bits */ virtual Qt::WindowFlags GetWindowFlags() const = 0; /** * Sets the style bits to use for the window's main widget when it is created. * This method has no effect after the widget is created. * That is, it must be called within the WorkbenchAdvisor#PreWindowOpen() * callback. *

* For more details on the applicable style bits, see the * documentation for Qt::WindowFlags. *

* * @param windowFlags the style bits */ virtual void SetWindowFlags(Qt::WindowFlags windowFlags) = 0; /** * Returns the size to use for the window's shell when it is created. * * @return the initial size to use for the shell */ - virtual Point GetInitialSize() const = 0; + virtual QPoint GetInitialSize() const = 0; /** * Sets the size to use for the window's shell when it is created. * This method has no effect after the shell is created. * That is, it must be called within the WorkbenchAdvisor#PreWindowOpen() * callback. * * @param initialSize the initial size to use for the shell */ - virtual void SetInitialSize(Point initialSize) = 0; + virtual void SetInitialSize(QPoint initialSize) = 0; /* * Returns the data associated with this workbench window at the given key. * * @param key the key * @return the data, or null if there is no data at the given * key */ //virtual Object getData(String key); /* * Sets the data associated with this workbench window at the given key. * * @param key the key * @param data the data, or null to delete existing data */ //virtual void setData(String key, Object data); /** * Adds the given drag and drop Mime types to the ones * supported for drag and drop on the editor area of this workbench window. *

* The workbench advisor would ordinarily call this method from the * PreWindowOpen callback. * A newly-created workbench window supports no drag and drop transfer * types. *

*

* Note that drag and drop to the editor area requires adding one or more * transfer types (using AddEditorAreaTransfer) and * configuring a drop target listener * (with ConfigureEditorAreaDropListener) * capable of handling any of those transfer types. *

* * @param transfer a drag and drop transfer object * @see #configureEditorAreaDropListener * @see org.blueberry.ui.part.EditorInputTransfer */ virtual void AddEditorAreaTransfer(const QStringList& transferTypes) = 0; /** * Configures the drop target listener for the editor area of this workbench window. *

* The workbench advisor ordinarily calls this method from the * PreWindowOpen callback. * A newly-created workbench window has no configured drop target listener for its * editor area. *

*

* Note that drag and drop to the editor area requires adding one or more * transfer types (using AddEditorAreaTransfer) and * configuring a drop target listener * (with ConfigureEditorAreaDropListener) * capable of handling any of those transfer types. *

* * @param dropTargetListener the drop target listener that will handle * requests to drop an object on to the editor area of this window * * @see #AddEditorAreaTransfer */ virtual void ConfigureEditorAreaDropListener(IDropTargetListener* dropTargetListener) = 0; /** * Creates the menu bar for the window's shell. *

* This should only be called if the advisor is defining custom window contents * in CreateWindowContents, and may only be called once. * The caller must set it in the shell using Shell.setMenuBar(Menu) * but must not make add, remove or change items in the result. * The menu bar is populated by the window's menu manager. * The application can add to the menu manager in the advisor's * FillActionBars method instead. *

* * @return the menu bar, suitable for setting in the shell */ virtual QMenuBar* CreateMenuBar() = 0; /** * Creates the tool bar control. *

* This should only be called if the advisor is defining custom window contents * in CreateWindowContents, and may only be called once. * The caller must lay out the tool bar appropriately within the parent, * but must not add, remove or change items in the result (hence the * return type of QWidget). * The tool bar is populated by the window's tool bar manager. * The application can add to the tool bar manager in the advisor's * FillActionBars method instead. *

* * @param parent the parent widget * @return the tool bar control, suitable for laying out in the parent */ virtual QWidget* CreateToolBar(QWidget* parent) = 0; /* * Creates the status line control. *

* This should only be called if the advisor is defining custom window contents * in createWindowContents, and may only be called once. * The caller must lay out the status line appropriately within the parent, * but must not add, remove or change items in the result (hence the * return type of Control). * The status line is populated by the window's status line manager. * The application can add to the status line manager in the advisor's * fillActionBars method instead. *

* * @param parent the parent composite * @return the status line control, suitable for laying out in the parent */ //virtual Control createStatusLineControl(Composite parent); /** * Creates the page composite, in which the window's pages, and their * views and editors, appear. *

* This should only be called if the advisor is defining custom window contents * in WorkbenchWindowAdvisor#CreateWindowContents(), and may only be called once. * The caller must lay out the page composite appropriately within the parent, * but must not add, remove or change items in the result. * The page composite is populated by the workbench. *

* * @param parent the parent composite * @return the page composite, suitable for laying out in the parent */ virtual QWidget* CreatePageComposite(QWidget* parent) = 0; /** * Saves the current state of the window using the specified memento. * * @param memento the memento in which to save the window's state * @return a status object indicating whether the save was successful * @see IWorkbenchConfigurer#RestoreWorkbenchWindow(IMemento::Pointer) */ virtual bool SaveState(SmartPointer memento) = 0; }; } #endif /*BERRYIWORKBENCHWINDOWCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryConstants.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryConstants.h index 69d398a2c9..1763fa8af9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryConstants.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryConstants.h @@ -1,309 +1,321 @@ /*=================================================================== 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 BERRYCONSTANTS_H_ #define BERRYCONSTANTS_H_ #include namespace berry { +enum CursorType +{ + CURSOR_INVALID, + CURSOR_LEFT, + CURSOR_RIGHT, + CURSOR_TOP, + CURSOR_BOTTOM, + CURSOR_CENTER, + CURSOR_OFFSCREEN, + CURSOR_FASTVIEW +}; + struct BERRY_UI_QT Constants { /** * A constant known to be zero (0), typically used in operations * which take bit flags to indicate that "no bits are set". */ static const int NONE; // = 0; static const int DEFAULT; // = -1 /** * Indicates that a user-interface component is being dragged, * for example dragging the thumb of a scroll bar (value is 1). */ static const int DRAG; // = 1; /** * Style constant for align center behavior (value is 1<<24). *

Used By:

    *
  • Button
  • *
  • Label
  • *
  • TableColumn
  • *
  • FormAttachment in a FormLayout
  • *

*/ static const int CENTER; // = 1 << 24; /** * Style constant for horizontal alignment or orientation behavior (value is 1<<8). *

Used By:

    *
  • Label
  • *
  • ProgressBar
  • *
  • Sash
  • *
  • Scale
  • *
  • ScrollBar
  • *
  • Slider
  • *
  • ToolBar
  • *
  • FillLayout type
  • *
  • RowLayout type
  • *

*/ static const int HORIZONTAL; // = 1 << 8; /** * Style constant for vertical alignment or orientation behavior (value is 1<<9). *

Used By:

    *
  • Label
  • *
  • ProgressBar
  • *
  • Sash
  • *
  • Scale
  • *
  • ScrollBar
  • *
  • Slider
  • *
  • ToolBar
  • *
  • CoolBar
  • *
  • FillLayout type
  • *
  • RowLayout type
  • *

*/ static const int VERTICAL; // = 1 << 9; /** * Style constant for minimize box trim (value is 1<<7). *

Used By:

    *
  • Decorations and subclasses
  • *

*/ static const int MIN; // = 1 << 7; /** * Style constant for maximize box trim (value is 1<<10). *

Used By:

    *
  • Decorations and subclasses
  • *

*/ static const int MAX; // = 1 << 10; /** * Style constant for align up behavior (value is 1<<7, * since align UP and align TOP are considered the same). *

Used By:

    *
  • Button with ARROW style
  • *
  • Tracker
  • *
  • Table
  • *
  • Tree
  • *

*/ static const int UP; // = 1 << 7; /** * Style constant for align top behavior (value is 1<<7, * since align UP and align TOP are considered the same). *

Used By:

    *
  • FormAttachment in a FormLayout
  • *

*/ static const int TOP; // = UP; /** * Style constant for align down behavior (value is 1<<10, * since align DOWN and align BOTTOM are considered the same). *

Used By:

    *
  • Button with ARROW style
  • *
  • Tracker
  • *
  • Table
  • *
  • Tree
  • *

*/ static const int DOWN; // = 1 << 10; /** * Style constant for align bottom behavior (value is 1<<10, * since align DOWN and align BOTTOM are considered the same). *

Used By:

    *
  • FormAttachment in a FormLayout
  • *

*/ static const int BOTTOM; // = DOWN; /** * Style constant for leading alignment (value is 1<<14). *

Used By:

    *
  • Button
  • *
  • Label
  • *
  • TableColumn
  • *
  • Tracker
  • *
  • FormAttachment in a FormLayout
  • *

* * @since 2.1.2 */ static const int LEAD; // = 1 << 14; /** * Style constant for align left behavior (value is 1<<14). * This is a synonym for LEAD (value is 1<<14). Newer * applications should use LEAD instead of LEFT to make code more * understandable on right-to-left platforms. */ static const int LEFT; // = LEAD; /** * Style constant for trailing alignment (value is 1<<17). *

Used By:

    *
  • Button
  • *
  • Label
  • *
  • TableColumn
  • *
  • Tracker
  • *
  • FormAttachment in a FormLayout
  • *

* * @since 2.1.2 */ static const int TRAIL; // = 1 << 17; /** * Style constant for align right behavior (value is 1<<17). * This is a synonym for TRAIL (value is 1<<17). Newer * applications should use TRAIL instead of RIGHT to make code more * understandable on right-to-left platforms. */ static const int RIGHT; // = TRAIL; /** * Style constant for vertical alignment or orientation behavior (value is 4). */ static const int FILL; // = 4; /** * Style constant for automatic line wrap behavior (value is 1<<6). */ static const int WRAP; // = 1 << 6; /** * Style constant for bordered behavior (value is 1<<11). *
Note that this is a HINT. *

Used By:

    *
  • Control and subclasses
  • *

*/ static const int BORDER; // = 1 << 11; /** * Style constant for close box trim (value is 1<<6, * since we do not distinguish between CLOSE style and MENU style). *

Used By:

    *
  • Decorations and subclasses
  • *

*/ static const int CLOSE; // = 1 << 6; /** * Style constant for tool window behavior (value is 1<<2). *

* A tool window is a window intended to be used as a floating toolbar. * It typically has a title bar that is shorter than a normal title bar, * and the window title is typically drawn using a smaller font. *
Note that this is a HINT. *

Used By:

    *
  • Decorations and subclasses
  • *

*/ static const int TOOL; // = 1 << 2; /** * Style constant for resize box trim (value is 1<<4). *

Used By:

    *
  • Decorations and subclasses
  • *
  • Tracker
  • *

*/ static const int RESIZE; // = 1 << 4; /** * Style constant for title area trim (value is 1<<5). *

Used By:

    *
  • Decorations and subclasses
  • *

*/ static const int TITLE; // = 1 << 5; /** * Trim style convenience constant for the most common top level shell appearance * (value is CLOSE|TITLE|MIN|MAX|RESIZE). *

Used By:

    *
  • Shell
  • *

*/ static const int SHELL_TRIM; // = CLOSE | TITLE | MIN | MAX | RESIZE; /** * Trim style convenience constant for the most common dialog shell appearance * (value is CLOSE|TITLE|BORDER). *

Used By:

    *
  • Shell
  • *

*/ static const int DIALOG_TRIM; // = TITLE | CLOSE | BORDER; /** * Style constant for modeless behavior (value is 0). *
Note that this is a HINT. *

Used By:

    *
  • Dialog
  • *
  • Shell
  • *

*/ static const int MODELESS; // = 0; /** * Style constant for primary modal behavior (value is 1<<15). *
Note that this is a HINT. *

Used By:

    *
  • Dialog
  • *
  • Shell
  • *

*/ static const int PRIMARY_MODAL; // = 1 << 15; /** * Style constant for application modal behavior (value is 1<<16). *
Note that this is a HINT. *

Used By:

    *
  • Dialog
  • *
  • Shell
  • *

*/ static const int APPLICATION_MODAL; // = 1 << 16; /** * Style constant for system modal behavior (value is 1<<17). *
Note that this is a HINT. *

Used By:

    *
  • Dialog
  • *
  • Shell
  • *

*/ static const int SYSTEM_MODAL; // = 1 << 17; }; } #endif /* BERRYCONSTANTS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp index a47b2613b6..59cb93cfec 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp @@ -1,166 +1,169 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryGeometry.h" #include "berryConstants.h" +#include +#include + #include namespace berry { -int Geometry::GetDimension(const Rectangle& toMeasure, bool width) +int Geometry::GetDimension(const QRect& toMeasure, bool width) { if (width) { - return toMeasure.width; + return toMeasure.width(); } - return toMeasure.height; + return toMeasure.height(); } bool Geometry::IsHorizontal(int berrySideConstant) { return !(berrySideConstant == Constants::LEFT || berrySideConstant == Constants::RIGHT); } -Rectangle Geometry::GetExtrudedEdge(const Rectangle& toExtrude, int size, +QRect Geometry::GetExtrudedEdge(const QRect& toExtrude, int size, int orientation) { - Rectangle bounds(toExtrude); + QRect bounds(toExtrude); if (!IsHorizontal(orientation)) { - bounds.width = size; + bounds.setWidth(size); } else { - bounds.height = size; + bounds.setHeight(size); } if (orientation == Constants::RIGHT) { - bounds.x = toExtrude.x + toExtrude.width - bounds.width; + bounds.moveLeft(toExtrude.x() + toExtrude.width() - bounds.width()); } else if (orientation == Constants::BOTTOM) { - bounds.y = toExtrude.y + toExtrude.height - bounds.height; + bounds.moveTop(toExtrude.y() + toExtrude.height() - bounds.height()); } Normalize(bounds); return bounds; } -void Geometry::Normalize(Rectangle& rect) +void Geometry::Normalize(QRect& rect) { - if (rect.width < 0) + if (rect.width() < 0) { - rect.width = -rect.width; - rect.x -= rect.width; + rect.setWidth(-rect.width()); + rect.setX(-rect.width()); } - if (rect.height < 0) + if (rect.height() < 0) { - rect.height = -rect.height; - rect.y -= rect.height; + rect.setHeight(-rect.height()); + rect.setY(-rect.height()); } } -int Geometry::GetClosestSide(const Rectangle& boundary, const Point& toTest) +int Geometry::GetClosestSide(const QRect& boundary, const QPoint& toTest) { int sides[] = { Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM }; int closestSide = Constants::LEFT; int closestDistance = std::numeric_limits::max(); for (unsigned int idx = 0; idx < 4; idx++) { int side = sides[idx]; int distance = GetDistanceFromEdge(boundary, toTest, side); if (distance < closestDistance) { closestDistance = distance; closestSide = side; } } return closestSide; } -int Geometry::GetDistanceFromEdge(const Rectangle& rectangle, - const Point& testPoint, int edgeOfInterest) +int Geometry::GetDistanceFromEdge(const QRect& rectangle, + const QPoint& testPoint, int edgeOfInterest) { if (edgeOfInterest == Constants::TOP) - return testPoint.y - rectangle.y; + return testPoint.y() - rectangle.y(); else if (edgeOfInterest == Constants::BOTTOM) - return rectangle.y + rectangle.height - testPoint.y; + return rectangle.y() + rectangle.height() - testPoint.y(); else if (edgeOfInterest == Constants::LEFT) - return testPoint.x - rectangle.x; + return testPoint.x() - rectangle.x(); else if (edgeOfInterest == Constants::RIGHT) - return rectangle.x + rectangle.width - testPoint.x; + return rectangle.x() + rectangle.width() - testPoint.x(); return 0; } int Geometry::GetOppositeSide(int directionConstant) { if (directionConstant == Constants::TOP) return Constants::BOTTOM; else if (directionConstant == Constants::BOTTOM) return Constants::TOP; else if (directionConstant == Constants::LEFT) return Constants::RIGHT; else if (directionConstant == Constants::RIGHT) return Constants::LEFT; return directionConstant; } -Rectangle Geometry::ToControl(void* coordinateSystem, - const Rectangle& toConvert) +QRect Geometry::ToControl(void* coordinateSystem, + const QRect& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, toConvert); } -Point Geometry::ToControl(void* coordinateSystem, const Point& toConvert) +QPoint Geometry::ToControl(void* coordinateSystem, const QPoint& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, toConvert); } -Rectangle Geometry::ToDisplay(void* coordinateSystem, - const Rectangle& toConvert) +QRect Geometry::ToDisplay(void* coordinateSystem, + const QRect& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, toConvert); } -Point Geometry::ToDisplay(void* coordinateSystem, const Point& toConvert) +QPoint Geometry::ToDisplay(void* coordinateSystem, const QPoint& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h index 891e8d8326..ee0c453512 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h @@ -1,163 +1,165 @@ /*=================================================================== 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 BERRYGEOMETRY_H_ #define BERRYGEOMETRY_H_ -#include "berryRectangle.h" -#include "berryPoint.h" +#include + +class QRect; +class QPoint; namespace berry { struct BERRY_UI_QT Geometry { /** * Returns the height or width of the given rectangle. * * @param toMeasure rectangle to measure * @param width returns the width if true, and the height if false * @return the width or height of the given rectangle * @since 3.0 */ - static int GetDimension(const Rectangle& toMeasure, bool width); + static int GetDimension(const QRect& toMeasure, bool width); /** * Returns true iff the given side constant corresponds to a horizontal side * of a rectangle. That is, returns true for the top and bottom but false for the * left and right. * * @param swtSideConstant one of Constants::TOP, Constants::BOTTOM, Constants::LEFT, or Constants::RIGHT * @return true iff the given side is horizontal. * @since 3.0 */ static bool IsHorizontal(int berrySideConstant); /** * Extrudes the given edge inward by the given distance. That is, if one side of the rectangle * was sliced off with a given thickness, this returns the rectangle that forms the slice. Note * that the returned rectangle will be inside the given rectangle if size > 0. * * @param toExtrude the rectangle to extrude. The resulting rectangle will share three sides * with this rectangle. * @param size distance to extrude. A negative size will extrude outwards (that is, the resulting * rectangle will overlap the original iff this is positive). * @param orientation the side to extrude. One of Constants::LEFT, Constants::RIGHT, Constants::TOP, or Constants::BOTTOM. The * resulting rectangle will always share this side with the original rectangle. * @return a rectangle formed by extruding the given side of the rectangle by the given distance. */ - static Rectangle GetExtrudedEdge(const Rectangle& toExtrude, int size, + static QRect GetExtrudedEdge(const QRect& toExtrude, int size, int orientation); /** * Normalizes the given rectangle. That is, any rectangle with * negative width or height becomes a rectangle with positive * width or height that extends to the upper-left of the original * rectangle. * * @param rect rectangle to modify */ - static void Normalize(Rectangle& rect); + static void Normalize(QRect& rect); /** * Returns the edge of the given rectangle is closest to the given * point. * * @param boundary rectangle to test * @param toTest point to compare * @return one of SWT.LEFT, SWT.RIGHT, SWT.TOP, or SWT.BOTTOM * * @since 3.0 */ - static int GetClosestSide(const Rectangle& boundary, const Point& toTest); + static int GetClosestSide(const QRect& boundary, const QPoint& toTest); /** * Returns the distance of the given point from a particular side of the given rectangle. * Returns negative values for points outside the rectangle. * * @param rectangle a bounding rectangle * @param testPoint a point to test * @param edgeOfInterest side of the rectangle to test against * @return the distance of the given point from the given edge of the rectangle * @since 3.0 */ - static int GetDistanceFromEdge(const Rectangle& rectangle, const Point& testPoint, + static int GetDistanceFromEdge(const QRect& rectangle, const QPoint& testPoint, int edgeOfInterest); /** * Returns the opposite of the given direction. That is, returns SWT.LEFT if * given SWT.RIGHT and visa-versa. * * @param swtDirectionConstant one of SWT.LEFT, SWT.RIGHT, SWT.TOP, or SWT.BOTTOM * @return one of SWT.LEFT, SWT.RIGHT, SWT.TOP, or SWT.BOTTOM * @since 3.0 */ static int GetOppositeSide(int directionConstant); /** * Converts the given rectangle from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert rectangle to convert * @return a rectangle in control coordinates * @since 3.0 */ - static Rectangle ToControl(void* coordinateSystem, - const Rectangle& toConvert); + static QRect ToControl(void* coordinateSystem, + const QRect& toConvert); /** * Converts the given point from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert point to convert * @return a point in control coordinates * @since 3.0 */ - static Point ToControl(void* coordinateSystem, - const Point& toConvert); + static QPoint ToControl(void* coordinateSystem, + const QPoint& toConvert); /** * Converts the given rectangle from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert rectangle to convert * @return a rectangle in display coordinates * @since 3.0 */ - static Rectangle ToDisplay(void* coordinateSystem, - const Rectangle& toConvert); + static QRect ToDisplay(void* coordinateSystem, + const QRect& toConvert); /** * Converts the given point from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert point to convert * @return a point in display coordinates * @since 3.0 */ - static Point ToDisplay(void* coordinateSystem, - const Point& toConvert); + static QPoint ToDisplay(void* coordinateSystem, + const QPoint& toConvert); }; } #endif /* BERRYGEOMETRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.cpp deleted file mode 100644 index 5f689a7a0f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.cpp +++ /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. - -===================================================================*/ - -#include "berryPoint.h" - -#include - -namespace berry -{ - -Point::Point(int x, int y) -{ - this->x = x; - this->y = y; -} - -bool Point::operator==(const Point& p) const -{ - if (&p == this) return true; - return (p.x == x) && (p.y == y); -} - -int Point::HashCode() -{ - return x ^ y; -} - -QString Point::ToString() const -{ - QString str; - QTextStream ss(&str); - ss << "Point {" << x << ", " << y << "}"; - return str; -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.h deleted file mode 100644 index 3849c2913d..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPoint.h +++ /dev/null @@ -1,110 +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 BERRYPOINT_H_ -#define BERRYPOINT_H_ - -#include - -#include - -namespace berry -{ - -/** - * Instances of this class represent places on the (x, y) - * coordinate plane. - *

- * The coordinate space for rectangles and points is considered - * to have increasing values downward and to the right from its - * origin making this the normal, computer graphics oriented notion - * of (x, y) coordinates rather than the strict mathematical one. - *

- *

- * The hashCode() method in this class uses the values of the public - * fields to compute the hash value. When storing instances of the - * class in hashed collections, do not modify these fields after the - * object has been inserted. - *

- *

- * Application code does not need to explicitly release the - * resources managed by each instance when those instances are no longer - * required, and thus no dispose() method is provided. - *

- * - * @see Rectangle - */ - -class BERRY_UI_QT Point -{ - -public: - - /** - * the x coordinate of the point - */ - int x; - - /** - * the y coordinate of the point - */ - int y; - - /** - * Constructs a new point with the given x and y coordinates. - * - * @param x the x coordinate of the new point - * @param y the y coordinate of the new point - */ - Point(int x, int y); - - /** - * Compares the argument to the receiver, and returns true - * if they represent the same object using a class - * specific comparison. - * - * @param object the object to compare with this object - * @return true if the object is the same as this object and false otherwise - * - * @see #hashCode() - */ - bool operator==(const Point& p) const; - - /** - * Returns an integer hash code for the receiver. Any two - * objects that return true when passed to - * equals must return the same value for this - * method. - * - * @return the receiver's hash - * - * @see #equals(Object) - */ - int HashCode(); - - /** - * Returns a string containing a concise, human-readable - * description of the receiver. - * - * @return a string representation of the point - */ - QString ToString() const; - -}; - -} - -#endif /*BERRYPOINT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.cpp deleted file mode 100644 index 0ea1f6cb10..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.cpp +++ /dev/null @@ -1,167 +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 "berryRectangle.h" - -#include - -namespace berry -{ - -Rectangle::Rectangle() -: x(0), y(0), width(0), height(0) -{ - -} - -Rectangle::Rectangle(int x_, int y_, int w, int h) : - x(x_), y(y_), width(w), height(h) -{ - -} - -void Rectangle::Add(const Rectangle& rect) -{ - int left = x < rect.x ? x : rect.x; - int top = y < rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs > rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs > rhs ? lhs : rhs; - x = left; - y = top; - width = right - left; - height = bottom - top; -} - -bool Rectangle::Contains(int x, int y) const -{ - return (x >= this->x) && (y >= this->y) && ((x - this->x) < width) && ((y - - this->y) < height); -} - -bool Rectangle::Contains(const Point& point) const -{ - return this->Contains(point.x, point.y); -} - -Rectangle& Rectangle::FlipXY() -{ - int tmp = x; - x = y; - y = tmp; - - tmp = width; - width = height; - height = tmp; - - return *this; -} - -bool Rectangle::operator==(const Rectangle& r) const -{ - if (&r == this) return true; - return (r.x == this->x) && (r.y == this->y) && (r.width == this->width) && (r.height == this->height); -} - -int Rectangle::HashCode() const -{ - return x ^ y ^ width ^ height; -} - -void Rectangle::Intersect(const Rectangle& rect) -{ - if (this == &rect) return; - int left = x> rect.x ? x : rect.x; - int top = y> rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs < rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs < rhs ? lhs : rhs; - x = right < left ? 0 : left; - y = bottom < top ? 0 : top; - width = right < left ? 0 : right - left; - height = bottom < top ? 0 : bottom - top; -} - -Rectangle Rectangle::Intersection(const Rectangle& rect) const -{ - if (this == &rect) return Rectangle (x, y, width, height); - int left = x> rect.x ? x : rect.x; - int top = y> rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs < rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs < rhs ? lhs : rhs; - return Rectangle ( - right < left ? 0 : left, - bottom < top ? 0 : top, - right < left ? 0 : right - left, - bottom < top ? 0 : bottom - top); -} - -bool Rectangle::Intersects(int x, int y, int width, int height) const -{ - return (x < this->x + this->width) && (y < this->y + this->height) && - (x + width> this->x) && (y + height> this->y); -} - -bool Rectangle::Intersects(const Rectangle& rect) const -{ - return &rect == this || this->Intersects(rect.x, rect.y, rect.width, rect.height); -} - -int Rectangle::GetDimension(bool width) const -{ - if (width) { - return this->width; - } - return this->height; -} - -bool Rectangle::IsEmpty () const -{ - return (width <= 0) || (height <= 0); -} - -QString Rectangle::ToString () const -{ - QString str; - QTextStream stream(&str); - stream << "Rectangle {" << x << ", " << y << ", " << width << ", " << height << "}"; - return str; -} - -Rectangle Rectangle::Union(const Rectangle& rect) const -{ - int left = x < rect.x ? x : rect.x; - int top = y < rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs> rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs> rhs ? lhs : rhs; - return Rectangle(left, top, right - left, bottom - top); -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.h deleted file mode 100644 index f033f9d7d0..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryRectangle.h +++ /dev/null @@ -1,295 +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 BERRYRECTANGLE_H_ -#define BERRYRECTANGLE_H_ - -#include -#include "berryPoint.h" - -#include - -namespace berry -{ - -/** - * Instances of this class represent rectangular areas in an - * (x, y) coordinate system. The top left corner of the rectangle - * is specified by its x and y values, and the extent of the - * rectangle is specified by its width and height. - *

- * The coordinate space for rectangles and points is considered - * to have increasing values downward and to the right from its - * origin making this the normal, computer graphics oriented notion - * of (x, y) coordinates rather than the strict mathematical one. - *

- *

- * The hashCode() method in this class uses the values of the - * fields to compute the hash value. When storing instances of the - * class in hashed collections, do not modify these fields after the - * object has been inserted. - *

- *

- * Application code does not need to explicitly release the - * resources managed by each instance when those instances are no longer - * required, and thus no dispose() method is provided. - *

- * - */ - -struct BERRY_UI_QT Rectangle -{ - - /** - * the x coordinate of the rectangle - */ - int x; - - /** - * the y coordinate of the rectangle - */ - int y; - - /** - * the width of the rectangle - */ - int width; - - /** - * the height of the rectangle - */ - int height; - - /** - * Constrcut a new instance of this class with - * x, y, width and height values set to zero. - */ - Rectangle(); - - /** - * Construct a new instance of this class given the - * x, y, width and height values. - * - * @param x the x coordinate of the origin of the rectangle - * @param y the y coordinate of the origin of the rectangle - * @param width the width of the rectangle - * @param height the height of the rectangle - */ - Rectangle(int x, int y, int width, int height); - - /** - * Destructively replaces the x, y, width and height values - * in the receiver with ones which represent the union of the - * rectangles specified by the receiver and the given rectangle. - *

- * The union of two rectangles is the smallest single rectangle - * that completely covers both of the areas covered by the two - * given rectangles. - *

- * - * @param rect the rectangle to merge with the receiver - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- */ - void Add(const Rectangle& rect); - - /** - * Returns true if the point specified by the - * arguments is inside the area specified by the receiver, - * and false otherwise. - * - * @param x the x coordinate of the point to test for containment - * @param y the y coordinate of the point to test for containment - * @return true if the rectangle contains the point and false otherwise - */ - bool Contains(int x, int y) const; - - /** - * Returns true if the point specified by the - * arguments is inside the area specified by the receiver, - * and false otherwise. - * - * @param the point to test for containment - * @return true if the rectangle contains the point and false otherwise - */ - bool Contains(const Point& point) const; - - /** - * Flips the x and y coordinates, i.e. rotates the rectangle about 90 degrees. - * - * @return the flipped rectangle - */ - Rectangle& FlipXY(); - - /** - * Compares the argument to the receiver, and returns true - * if they represent the same object using a class - * specific comparison. - * - * @param object the object to compare with this object - * @return true if the object is the same as this object and false otherwise - * - * @see #hashCode() - */ - bool operator==(const Rectangle& object) const; - - /** - * Returns an integer hash code for the receiver. Any two - * objects that return true when passed to - * equals must return the same value for this - * method. - * - * @return the receiver's hash - * - * @see #equals(Object) - */ - int HashCode() const; - - /** - * Destructively replaces the x, y, width and height values - * in the receiver with ones which represent the intersection of the - * rectangles specified by the receiver and the given rectangle. - * - * @param rect the rectangle to intersect with the receiver - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- * - * since 3.0 - */ - void Intersect(const Rectangle& rect); - - /** - * Returns a new rectangle which represents the intersection - * of the receiver and the given rectangle. - *

- * The intersection of two rectangles is the rectangle that - * covers the area which is contained within both rectangles. - *

- * - * @param rect the rectangle to intersect with the receiver - * @return the intersection of the receiver and the argument - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- */ - Rectangle Intersection(const Rectangle& rect) const; - - /** - * Returns true if the rectangle described by the - * arguments intersects with the receiver and false - * otherwise. - *

- * Two rectangles intersect if the area of the rectangle - * representing their intersection is not empty. - *

- * - * @param x the x coordinate of the origin of the rectangle - * @param y the y coordinate of the origin of the rectangle - * @param width the width of the rectangle - * @param height the height of the rectangle - * @return true if the rectangle intersects with the receiver, and false otherwise - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- * - * @see #intersection(Rectangle) - * @see #isEmpty() - * - * @since 3.0 - */ - bool Intersects(int x, int y, int width, int height) const; - - /** - * Returns true if the given rectangle intersects - * with the receiver and false otherwise. - *

- * Two rectangles intersect if the area of the rectangle - * representing their intersection is not empty. - *

- * - * @param rect the rectangle to test for intersection - * @return true if the rectangle intersects with the receiver, and false otherwise - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- * - * @see #intersection(Rectangle) - * @see #isEmpty() - */ - bool Intersects(const Rectangle& rect) const; - - /** - * Returns the height or width - * - * @param width returns the width if true, and the height if false - * @return the width or height of the reciever - * @since 3.0 - */ - int GetDimension(bool width) const; - - /** - * Returns true if the receiver does not cover any - * area in the (x, y) coordinate plane, and false if - * the receiver does cover some area in the plane. - *

- * A rectangle is considered to cover area in the - * (x, y) coordinate plane if both its width and height are - * non-zero. - *

- * - * @return true if the receiver is empty, and false otherwise - */ - bool IsEmpty() const; - - /** - * Returns a string containing a concise, human-readable - * description of the receiver. - * - * @return a string representation of the rectangle - */ - QString ToString() const; - - /** - * Returns a new rectangle which represents the union of - * the receiver and the given rectangle. - *

- * The union of two rectangles is the smallest single rectangle - * that completely covers both of the areas covered by the two - * given rectangles. - *

- * - * @param rect the rectangle to perform union with - * @return the union of the receiver and the argument - * - * @exception IllegalArgumentException
    - *
  • ERROR_NULL_ARGUMENT - if the argument is null
  • - *
- * - * @see #add(Rectangle) - */ - Rectangle Union(const Rectangle& rect) const; - -}; - -} -#endif /*BERRYRECTANGLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp index 7eab010ffe..7edb166d85 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp @@ -1,54 +1,56 @@ /*=================================================================== 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 "berryShell.h" +#include + namespace berry { Shell::Shell() : extraShellListener(NULL) { } Object::Pointer Shell::GetData(const QString& id) const { QHash::const_iterator iter = data.find(id); if (iter == data.end()) return Object::Pointer(0); return iter.value(); } void Shell::SetData(const Object::Pointer& data, const QString& id) { this->data[id] = data; } IShellListener* Shell::GetExtraShellListener() const { return extraShellListener; } void Shell::SetExtraShellListener(IShellListener* l) { extraShellListener = l; } void Shell::SetBounds(int x, int y, int width, int height) { - Rectangle rect(x, y, width, height); + QRect rect(x, y, width, height); this->SetBounds(rect); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h index b179bcd881..d58edeb19c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h @@ -1,338 +1,334 @@ /*=================================================================== 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 BERRYSHELL_H_ #define BERRYSHELL_H_ #include #include #include "berryIShellListener.h" #include "guitk/berryGuiTkIControlListener.h" -#include "berryRectangle.h" -#include "berryPoint.h" - -#include namespace berry { /** * Instances of this class represent the "windows" * which the desktop or "window manager" is managing. * Instances that do not have a parent (that is, they * are built using the constructor, which takes a * Display as the argument) are described * as top level shells. Instances that do have * a parent are described as secondary or * dialog shells. *

* Instances are always displayed in one of the maximized, * minimized or normal states: *

    *
  • * When an instance is marked as maximized, the * window manager will typically resize it to fill the * entire visible area of the display, and the instance * is usually put in a state where it can not be resized * (even if it has style RESIZE) until it is * no longer maximized. *
  • * When an instance is in the normal state (neither * maximized or minimized), its appearance is controlled by * the style constants which were specified when it was created * and the restrictions of the window manager (see below). *
  • * When an instance has been marked as minimized, * its contents (client area) will usually not be visible, * and depending on the window manager, it may be * "iconified" (that is, replaced on the desktop by a small * simplified representation of itself), relocated to a * distinguished area of the screen, or hidden. Combinations * of these changes are also possible. *
  • *
*

* The modality of an instance may be specified using * style bits. The modality style bits are used to determine * whether input is blocked for other shells on the display. * The PRIMARY_MODAL style allows an instance to block * input to its parent. The APPLICATION_MODAL style * allows an instance to block input to every other shell in the * display. The SYSTEM_MODAL style allows an instance * to block input to all shells, including shells belonging to * different applications. *

* Note: The styles supported by this class are treated * as HINTs, since the window manager for the * desktop on which the instance is visible has ultimate * control over the appearance and behavior of decorations * and modality. For example, some window managers only * support resizable windows and will always assume the * RESIZE style, even if it is not set. In addition, if a * modality style is not supported, it is "upgraded" to a * more restrictive modality style that is supported. For * example, if PRIMARY_MODAL is not supported, * it would be upgraded to APPLICATION_MODAL. * A modality style may also be "downgraded" to a less * restrictive style. For example, most operating systems * no longer support SYSTEM_MODAL because * it can freeze up the desktop, so this is typically * downgraded to APPLICATION_MODAL. *

*
Styles:
*
BORDER, CLOSE, MIN, MAX, NO_TRIM, RESIZE, TITLE, ON_TOP, TOOL
*
APPLICATION_MODAL, MODELESS, PRIMARY_MODAL, SYSTEM_MODAL
*
Events:
*
Activate, Close, Deactivate, Deiconify, Iconify
*
* Class SWT provides two "convenience constants" * for the most commonly required style combinations: *
*
SHELL_TRIM
*
* the result of combining the constants which are required * to produce a typical application top level shell: (that * is, CLOSE | TITLE | MIN | MAX | RESIZE) *
*
DIALOG_TRIM
*
* the result of combining the constants which are required * to produce a typical application dialog shell: (that * is, TITLE | CLOSE | BORDER) *
*
*

*

* Note: Only one of the styles APPLICATION_MODAL, MODELESS, * PRIMARY_MODAL and SYSTEM_MODAL may be specified. *

* IMPORTANT: This class is not intended to be subclassed. *

* * @see Decorations * @see SWT * @see Shell snippets * @see SWT Example: ControlExample * @see Sample code and further information */ class BERRY_UI_QT Shell : public virtual Object { public: berryObjectMacro(Shell) Shell(); Object::Pointer GetData(const QString& id = "") const; void SetData(const Object::Pointer& data, const QString& id = ""); IShellListener* GetExtraShellListener() const; void SetExtraShellListener(IShellListener* l); void SetBounds(int x, int y, int width, int height); - virtual void SetBounds(const Rectangle& bounds) = 0; - virtual Rectangle GetBounds() const = 0; + virtual void SetBounds(const QRect& bounds) = 0; + virtual QRect GetBounds() const = 0; virtual void SetLocation(int x, int y) = 0; - virtual Point ComputeSize(int wHint, int hHint, bool changed) = 0; + virtual QPoint ComputeSize(int wHint, int hHint, bool changed) = 0; /** * Returns the receiver's text, which is the string that the * window manager will typically display as the receiver's title. * If the text has not previously been set, returns an empty string. * * @return the text */ virtual QString GetText() const = 0; /** * Sets the receiver's text, which is the string that the window manager * will typically display as the receiver's title, to the argument. */ virtual void SetText(const QString& text) = 0; virtual bool IsVisible() = 0; virtual void SetVisible(bool visible) = 0; virtual QWidget* GetControl() = 0; virtual void SetImages(const QList& images) = 0; /** * Returns true if the receiver is currently * maximized, and false otherwise. *

* * @return the maximized state * * @see #SetMaximized */ virtual bool GetMaximized() = 0; /** * Returns true if the receiver is currently * minimized, and false otherwise. *

* * @return the minimized state * * @see #SetMinimized */ virtual bool GetMinimized() = 0; /** * Sets the minimized stated of the receiver. * If the argument is true causes the receiver * to switch to the minimized state, and if the argument is * false and the receiver was previously minimized, * causes the receiver to switch back to either the maximized * or normal states. *

* Note: The result of intermixing calls to setMaximized(true) * and setMinimized(true) will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. *

* * @param minimized the new maximized state * * @see #SetMaximized */ virtual void SetMinimized(bool minimized) = 0; /** * Sets the maximized state of the receiver. * If the argument is true causes the receiver * to switch to the maximized state, and if the argument is * false and the receiver was previously maximized, * causes the receiver to switch back to either the minimized * or normal states. *

* Note: The result of intermixing calls to setMaximized(true) * and setMinimized(true) will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. *

* * @param maximized the new maximized state * * @see #SetMinimized */ virtual void SetMaximized(bool maximized) = 0; /** * Adds the listener to the collection of listeners who will * be notified when operations are performed on the receiver, * by sending the listener one of the messages defined in the * IShellListener interface. * * @param listener the listener which should be notified * * @see IShellListener * @see #RemoveShellListener */ virtual void AddShellListener(IShellListener* listener) = 0; /** * Removes the listener from the collection of listeners who will * be notified when operations are performed on the receiver. * * @param listener the listener which should no longer be notified * * @see IShellListener * @see #AddShellListener */ virtual void RemoveShellListener(IShellListener* listener) = 0; /** * Moves the receiver to the top of the drawing order for * the display on which it was created (so that all other * shells on that display, which are not the receiver's * children will be drawn behind it), marks it visible, * sets the focus and asks the window manager to make the * shell active. */ virtual void Open(bool block = false) = 0; /** * Requests that the window manager close the receiver in * the same way it would be closed when the user clicks on * the "close box" or performs some other platform specific * key or mouse combination that indicates the window * should be removed. */ virtual void Close() = 0; /** * If the receiver is visible, moves it to the top of the * drawing order for the display on which it was created * (so that all other shells on that display, which are not * the receiver's children will be drawn behind it) and * asks the window manager to make the shell active. */ virtual void SetActive() = 0; /** * Returns an array containing all shells which are * descendants of the receiver. *

* @return the dialog shells * * @exception SWTException

    *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • *
*/ virtual QList GetShells() = 0; /** * Returns the receiver's style information. *

* Note that the value which is returned by this method may * not match the value which was provided to the constructor * when the receiver was created. This can occur when the underlying * operating system does not support a particular combination of * requested styles. For example, if the platform widget used to * implement a particular SWT widget always has scroll bars, the * result of calling this method would always have the * SWT.H_SCROLL and SWT.V_SCROLL bits set. *

* * @return the style bits * * @exception SWTException
    *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • *
*/ virtual Qt::WindowFlags GetStyle () const = 0; private: QHash data; IShellListener* extraShellListener; }; } Q_DECLARE_METATYPE(berry::Shell*) #endif /* BERRYSHELL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp index 531caa4669..dd84deeac3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp @@ -1,580 +1,580 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryWindow.h" #include "berryConstants.h" #include "berrySameShellProvider.h" #include "berryMenuManager.h" #include namespace berry { const int Window::OK = 0; const int Window::CANCEL = 1; QList Window::defaultImages = QList(); Window::IExceptionHandler::Pointer Window::exceptionHandler(new DefaultExceptionHandler()); IShellProvider::Pointer Window::defaultModalParent(new DefaultModalParent()); Window::WindowShellListener::WindowShellListener(Window* wnd) : window(wnd) { } void Window::WindowShellListener::ShellClosed(const ShellEvent::Pointer& event) { event->doit = false; // don't close now if (window->CanHandleShellCloseEvent()) { window->HandleShellCloseEvent(); } } void Window::DefaultExceptionHandler::HandleException(const std::exception& t) { // Try to keep running. std::cerr << t.what(); } Shell::Pointer Window::DefaultModalParent::GetShell() const { Shell::Pointer parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetActiveShell(); // Make sure we don't pick a parent that has a modal child (this can lock the app) if (parent == 0) { // If this is a top-level window, then there must not be any open modal windows. parent = Window::GetModalChild(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShells()); } else { // If we picked a parent with a modal child, use the modal child instead Shell::Pointer modalChild = Window::GetModalChild(parent->GetShells()); if (modalChild != 0) { parent = modalChild; } } return parent; } Shell::Pointer Window::GetModalChild(const QList& toSearch) { int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; size_t size = toSearch.size(); for (size_t i = size - 1; i < size; i--) { Shell::Pointer shell = toSearch[i]; // Check if this shell has a modal child QList children = shell->GetShells(); Shell::Pointer modalChild = GetModalChild(children); if (modalChild != 0) { return modalChild; } // If not, check if this shell is modal itself if (shell->IsVisible() && (shell->GetStyle() & modal) != 0) { return shell; } } return Shell::Pointer(0); } //void Window::RunEventLoop() //{ // // //Use the display provided by the shell if possible // Display display; // if (shell == null) // { // display = Display.getCurrent(); // } // else // { // display = loopShell.getDisplay(); // } // // while (loopShell != null && !loopShell.isDisposed()) // { // try // { // if (!display.readAndDispatch()) // { // display.sleep(); // } // } catch (Throwable e) // { // exceptionHandler.handleException(e); // } // } // display.update(); //} Window::Window(Shell::Pointer parentShell) { this->parentShell = new SameShellProvider(parentShell); this->Init(); } Window::Window(IShellProvider::Pointer shellProvider) { poco_assert(shellProvider != 0); this->parentShell = shellProvider; this->Init(); } Window::~Window() { } void Window::Init() { this->shellStyle = Constants::SHELL_TRIM; this->returnCode = OK; this->block = false; } bool Window::CanHandleShellCloseEvent() { return true; } void Window::ConfigureShell(Shell::Pointer newShell) { // The single image version of this code had a comment related to bug // 46624, // and some code that did nothing if the stored image was already // disposed. // The equivalent in the multi-image version seems to be to remove the // disposed images from the array passed to the shell. if (defaultImages.size() > 0) { // ArrayList nonDisposedImages = new ArrayList(defaultImages.length); // for (int i = 0; i < defaultImages.length; ++i) // { // if (defaultImages[i] != null && !defaultImages[i].isDisposed()) // { // nonDisposedImages.add(defaultImages[i]); // } // } // // if (nonDisposedImages.size() <= 0) // { // System.err.println("Window.configureShell: images disposed"); //$NON-NLS-1$ // } // else // { // //Image[] array = new Image[nonDisposedImages.size()]; // nonDisposedImages.toArray(array); newShell->SetImages(defaultImages); // } } // Layout layout = getLayout(); // if (layout != null) // { // newShell.setLayout(layout); // } CreateTrimWidgets(newShell); } //voidWindow::ConstrainShellSize() //{ // // limit the shell size to the display size -// Rectangle bounds = shell.getBounds(); -// Rectangle constrained = getConstrainedShellBounds(bounds); +// QRect bounds = shell.getBounds(); +// QRect constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} void* Window::CreateContents(Shell::Pointer parent) { // by default, just create a composite //return new Composite(parent, SWT.NONE); return parent->GetControl(); } Shell::Pointer Window::CreateShell() { Shell::Pointer newParent = this->GetParentShell(); // if (newParent != 0 && newParent.isDisposed()) // { // parentShell = new SameShellProvider(null); // newParent = getParentShell();//Find a better parent // } //Create the shell Shell::Pointer newShell = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(newParent, this->GetShellStyle()); // resizeListener = new Listener() { // public void handleEvent(Event e) { // resizeHasOccurred = true; // } // }; //newShell.addListener(SWT.Resize, resizeListener); newShell->SetData(Object::Pointer(this)); //Add a listener newShell->AddShellListener(this->GetShellListener()); //Set the layout this->ConfigureShell(newShell); // //Register for font changes // if (fontChangeListener == null) // { // fontChangeListener = new FontChangeListener(); // } // JFaceResources.getFontRegistry().addListener(fontChangeListener); return newShell; } void* Window::GetContents() { return contents; } -Point Window::GetInitialLocation(const Point& initialSize) +QPoint Window::GetInitialLocation(const QPoint& initialSize) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); - Point centerPoint(0,0); - Rectangle parentBounds(0,0,0,0); + QPoint centerPoint(0,0); + QRect parentBounds(0,0,0,0); if (parent != 0) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); - centerPoint.x = parentBounds.x + parentBounds.width/2; - centerPoint.y = parentBounds.y - parentBounds.height/2; + centerPoint.setX(parentBounds.x() + parentBounds.width()/2); + centerPoint.setY(parentBounds.y() - parentBounds.height()/2); } else { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY) ->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber()); - centerPoint.x = parentBounds.width/2; - centerPoint.y = parentBounds.height/2; + centerPoint.setX(parentBounds.width()/2); + centerPoint.setY(parentBounds.height()/2); } - return Point(centerPoint.x - (initialSize.x / 2), - std::max(parentBounds.y, - std::min(centerPoint.y - (initialSize.y * 2 / 3), - parentBounds.y + parentBounds.height - initialSize.y))); + return QPoint(centerPoint.x() - (initialSize.x() / 2), + std::max(parentBounds.y(), + std::min(centerPoint.y() - (initialSize.y() * 2 / 3), + parentBounds.y() + parentBounds.height() - initialSize.y()))); } -Point Window::GetInitialSize() +QPoint Window::GetInitialSize() { return shell->ComputeSize(Constants::DEFAULT, Constants::DEFAULT, true); } Shell::Pointer Window::GetParentShell() { Shell::Pointer parent = parentShell->GetShell(); int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; if ((this->GetShellStyle() & modal) != 0) { // If this is a modal shell with no parent, pick a shell using defaultModalParent. if (parent == 0) { parent = defaultModalParent->GetShell(); } } return parent; } IShellListener* Window::GetShellListener() { if (windowShellListener.isNull()) windowShellListener.reset(new WindowShellListener(this)); return windowShellListener.data(); } int Window::GetShellStyle() { return shellStyle; } void Window::HandleShellCloseEvent() { this->SetReturnCode(CANCEL); this->Close(); } void Window::InitializeBounds() { // if (resizeListener != null) // { // shell.removeListener(SWT.Resize, resizeListener); // } // if (resizeHasOccurred) // { // Check if shell size has been set already. // return; // } - Point size = this->GetInitialSize(); - Point location = this->GetInitialLocation(size); - shell->SetBounds(this->GetConstrainedShellBounds(Rectangle(location.x, location.y, size.x, size.y))); + QPoint size = this->GetInitialSize(); + QPoint location = this->GetInitialLocation(size); + shell->SetBounds(this->GetConstrainedShellBounds(QRect(location.x(), location.y(), size.x(), size.y()))); } -Rectangle Window::GetConstrainedShellBounds(const Rectangle& preferredSize) +QRect Window::GetConstrainedShellBounds(const QRect& preferredSize) { - Rectangle result(preferredSize); + QRect result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); - Rectangle bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); + QRect bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); - if (result.height > bounds.height) { - result.height = bounds.height; + if (result.height() > bounds.height()) { + result.setHeight(bounds.height()); } - if (result.width > bounds.width) { - result.width = bounds.width; + if (result.width() > bounds.width()) { + result.setWidth(bounds.width()); } - result.x = std::max(bounds.x, std::min(result.x, bounds.x - + bounds.width - result.width)); - result.y = std::max(bounds.y, std::min(result.y, bounds.y - + bounds.height - result.height)); + result.setX( std::max(bounds.x(), std::min(result.x(), bounds.x() + + bounds.width() - result.width()))); + result.setY(std::max(bounds.y(), std::min(result.y(), bounds.y() + + bounds.height() - result.height()))); return result; } void Window::SetParentShell(Shell::Pointer newParentShell) { poco_assert(shell == 0); // "There must not be an existing shell."; //$NON-NLS-1$ parentShell = new SameShellProvider(newParentShell); } void Window::SetReturnCode(int code) { returnCode = code; } void Window::SetShellStyle(int newShellStyle) { shellStyle = newShellStyle; } void Window::AddMenuBar() { if (GetShell().IsNull() && menuBarManager.IsNull()) { menuBarManager = CreateMenuManager(); } } SmartPointer Window::CreateMenuManager() { MenuManager::Pointer manager(new MenuManager()); return manager; } void Window::CreateTrimWidgets(SmartPointer shell) { if (menuBarManager.IsNotNull()) { QMainWindow* mw = qobject_cast(shell->GetControl()); if (mw) { mw->setMenuBar(menuBarManager->CreateMenuBar(shell->GetControl())); menuBarManager->UpdateAll(true); } } // if (showTopSeperator()) // { // seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); // } //CreateToolBarControl(shell); //CreateStatusLine(shell); } bool Window::Close() { // BERRY_INFO << "Window::Close()"; // // stop listening for font changes // if (fontChangeListener != null) // { // JFaceResources.getFontRegistry().removeListener(fontChangeListener); // fontChangeListener = null; // } // remove this window from a window manager if it has one if (windowManager != 0) { windowManager->Remove(Window::Pointer(this)); windowManager = 0; } if (shell == 0) { return true; } shell->RemoveShellListener(this->GetShellListener()); shell->SetData(Object::Pointer(0)); // If we "close" the shell recursion will occur. // Instead, we need to "dispose" the shell to remove it from the // display. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->DisposeShell(shell); shell = 0; contents = 0; return true; } void Window::Create() { shell = this->CreateShell(); contents = this->CreateContents(shell); //initialize the bounds of the shell to that appropriate for the // contents this->InitializeBounds(); } void* Window::GetDefaultImage() { return (defaultImages.size() < 1) ? 0 : defaultImages[0]; } QList Window::GetDefaultImages() { return defaultImages; } int Window::GetReturnCode() { return returnCode; } Shell::Pointer Window::GetShell() const { return shell; } WindowManager* Window::GetWindowManager() { return windowManager; } MenuManager *Window::GetMenuBarManager() const { return menuBarManager.GetPointer(); } int Window::Open() { if (shell == 0) { // create the window this->Create(); } // limit the shell size to the display size //constrainShellSize(); // open the window shell->Open(block); // // run the event loop if specified // if (block) // { // this->RunEventLoop(); // } return returnCode; } void Window::SetBlockOnOpen(bool shouldBlock) { block = shouldBlock; } void Window::SetDefaultImage(void* image) { if (image != 0) defaultImages.push_back(image); } void Window::SetDefaultImages(const QList& images) { defaultImages = images; } void Window::SetWindowManager(WindowManager* manager) { windowManager = manager; // Code to detect invalid usage if (manager != 0) { QList windows = manager->GetWindows(); for (int i = 0; i < windows.size(); i++) { if (windows[i] == this) { return; } } manager->Add(Window::Pointer(this)); } } void Window::SetExceptionHandler(IExceptionHandler::Pointer handler) { if (exceptionHandler == 0) { exceptionHandler = handler; } } void Window::SetDefaultModalParent(IShellProvider::Pointer provider) { defaultModalParent = provider; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h index ea8a17c847..8c6271eced 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h @@ -1,732 +1,731 @@ /*=================================================================== 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 BERRYWINDOW_H_ #define BERRYWINDOW_H_ #include #include "berryIShellProvider.h" #include "berryIShellListener.h" -#include "berryPoint.h" #include "internal/berryWindowManager.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { //struct IToolBarManager; class MenuManager; //class StatusLineManager; /** * A JFace window is an object that has no visual representation (no widgets) * until it is told to open. *

* Creating a window involves the following steps: *

    *
  • creating an instance of a concrete subclass of Window *
  • *
  • creating the window's shell and widget tree by calling * create (optional)
  • *
  • assigning the window to a window manager using * WindowManager.add (optional)
  • *
  • opening the window by calling open
  • *
* Opening the window will create its shell and widget tree if they have not * already been created. When the window is closed, the shell and widget tree * are disposed of and are no longer referenced, and the window is automatically * removed from its window manager. A window may be reopened. *

*

* The JFace window framework (this package) consists of this class, * Window, the abstract base of all windows, and one concrete * window classes (ApplicationWindow) which may also be * subclassed. Clients may define additional window subclasses as required. *

*

* The Window class provides methods that subclasses may * override to configure the window, including: *

    *
  • close- extend to free other SWT resources
  • *
  • configureShell- extend or reimplement to set shell * properties before window opens
  • *
  • createContents- extend or reimplement to create controls * before window opens
  • *
  • getInitialSize- reimplement to give the initial size for * the shell
  • *
  • getInitialLocation- reimplement to give the initial * location for the shell
  • *
  • getShellListener- extend or reimplement to receive shell * events
  • *
  • handleFontChange- reimplement to respond to font changes *
  • *
  • handleShellCloseEvent- extend or reimplement to handle * shell closings
  • *
*

*/ class BERRY_UI_QT Window: public IShellProvider { public: berryObjectMacro(Window); /** * Standard return code constant (value 0) indicating that the window was * opened. * * @see #open */ static const int OK; // = 0; /** * Standard return code constant (value 1) indicating that the window was * canceled. * * @see #open */ static const int CANCEL; // = 1; /** * An array of images to be used for the window. It is expected that the * array will contain the same icon rendered at different resolutions. */ static QList defaultImages; /** * This interface defines a Exception Handler which can be set as a global * handler and will be called if an exception happens in the event loop. */ struct IExceptionHandler: public Object { berryObjectMacro(IExceptionHandler) /** * Handle the exception. * * @param t * The exception that occured. */ virtual void HandleException(const std::exception& t) = 0; }; private: struct WindowShellListener : public IShellListener { WindowShellListener(Window* wnd); void ShellClosed(const ShellEvent::Pointer& event); private: Window* window; }; QScopedPointer windowShellListener; /** * Defines a default exception handler. */ struct DefaultExceptionHandler: public IExceptionHandler { /* * (non-Javadoc) * * @see org.blueberry.jface.window.Window.IExceptionHandler#handleException(java.lang.Throwable) */ void HandleException(const std::exception& t); }; /** * Menu bar manager, or null if none (default). * * @see #addMenuBar */ SmartPointer menuBarManager; /** * Tool bar manager, or null if none (default). * * @see #addToolBar */ //SmartPointer toolBarManager; /** * Status line manager, or null if none (default). * * @see #addStatusLine */ //SmartPointer statusLineManager; /** * The exception handler for this application. */ static IExceptionHandler::Pointer exceptionHandler; /** * Object used to locate the default parent for modal shells */ struct DefaultModalParent: public IShellProvider { Shell::Pointer GetShell() const; }; friend struct DefaultModalParent; static IShellProvider::Pointer defaultModalParent; /** * Object that returns the parent shell. */ IShellProvider::Pointer parentShell; /** * Shell style bits. * * @see #setShellStyle */ int shellStyle; // = Constants::SHELL_TRIM; /** * Window manager, or null if none. * * @see #setWindowManager */ WindowManager* windowManager; /** * Window shell, or null if none. */ Shell::Pointer shell; /** * Top level SWT control, or null if none */ void* contents; /** * Window return code; initially OK. * * @see #setReturnCode */ int returnCode; // = OK; /** * true if the open method should not return * until the window closes, and false if the * open method should return immediately; initially * false (non-blocking). * * @see #setBlockOnOpen */ bool block; // = false; // /** // * Internal class for informing this window when fonts change. // */ // class FontChangeListener implements IPropertyChangeListener { // public void propertyChange(PropertyChangeEvent event) { // handleFontChange(event); // } // } // /** // * Internal font change listener. // */ // private FontChangeListener fontChangeListener; /** * Internal fields to detect if shell size has been set */ //bool resizeHasOccurred = false; //Listener resizeListener; /** * Returns the most specific modal child from the given list of Shells. * * @param toSearch shells to search for modal children * @return the most specific modal child, or null if none * * @since 3.1 */ static Shell::Pointer GetModalChild( const QList& toSearch); /** * Runs the event loop for the given shell. * * @param loopShell * the shell */ //void RunEventLoop(); protected: /** * Creates a window instance, whose shell will be created under the given * parent shell. Note that the window will have no visual representation * until it is told to open. By default, open does not block. * * @param parentShell * the parent shell, or null to create a top-level * shell. Try passing "(Shell)null" to this method instead of "null" * if your compiler complains about an ambiguity error. * @see #setBlockOnOpen * @see #getDefaultOrientation() */ Window(Shell::Pointer parentShell); /** * Creates a new window which will create its shell as a child of whatever * the given shellProvider returns. * * @param shellProvider object that will return the current parent shell. Not null. * */ Window(IShellProvider::Pointer shellProvider); ~Window(); /** * Given the desired position of the window, this method returns an adjusted * position such that the window is no larger than its monitor, and does not * extend beyond the edge of the monitor. This is used for computing the * initial window position, and subclasses can use this as a utility method * if they want to limit the region in which the window may be moved. * * @param preferredSize * the preferred position of the window * @return a rectangle as close as possible to preferredSize that does not * extend outside the monitor * */ - Rectangle GetConstrainedShellBounds(const Rectangle& preferredSize); + QRect GetConstrainedShellBounds(const QRect& preferredSize); /** * Initializes this windows variables */ virtual void Init(); /** * Determines if the window should handle the close event or do nothing. *

* The default implementation of this framework method returns * true, which will allow the * handleShellCloseEvent method to be called. Subclasses may * extend or reimplement. *

* * @return whether the window should handle the close event. */ virtual bool CanHandleShellCloseEvent(); /** * Configures the given shell in preparation for opening this window in it. *

* The default implementation of this framework method sets the shell's * image and gives it a grid layout. Subclasses may extend or reimplement. *

* * @param newShell * the shell */ virtual void ConfigureShell(Shell::Pointer newShell); /** * Constrain the shell size to be no larger than the display bounds. * * @since 2.0 */ //void ConstrainShellSize(); /** * Creates and returns this window's contents. Subclasses may attach any * number of children to the parent. As a convenience, the return value of * this method will be remembered and returned by subsequent calls to * getContents(). Subclasses may modify the parent's layout if they overload * getLayout() to return null. * *

* It is common practise to create and return a single composite that * contains the entire window contents. *

* *

* The default implementation of this framework method creates an instance * of Composite. Subclasses may override. *

* * @param parent * the parent composite for the controls in this window. The type * of layout used is determined by getLayout() * * @return the control that will be returned by subsequent calls to * getContents() */ virtual void* CreateContents(Shell::Pointer parent); /** * Creates and returns this window's shell. *

* The default implementation of this framework method creates a new shell * and configures it using configureShell. Rather than * override this method, subclasses should instead override * configureShell. *

* * @return the shell */ virtual Shell::Pointer CreateShell(); /** * Returns the top level control for this window. The parent of this control * is the shell. * * @return the top level control, or null if this window's * control has not been created yet */ virtual void* GetContents(); /** * Returns the initial location to use for the shell. The default * implementation centers the shell horizontally (1/2 of the difference to * the left and 1/2 to the right) and vertically (1/3 above and 2/3 below) * relative to the parent shell, or display bounds if there is no parent * shell. * * @param initialSize * the initial size of the shell, as returned by * getInitialSize. * @return the initial location of the shell */ - virtual Point GetInitialLocation(const Point& initialSize); + virtual QPoint GetInitialLocation(const QPoint& initialSize); /** * Returns the initial size to use for the shell. The default implementation * returns the preferred size of the shell, using * Shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true). * * @return the initial size of the shell */ - virtual Point GetInitialSize(); + virtual QPoint GetInitialSize(); /** * Returns parent shell, under which this window's shell is created. * * @return the parent shell, or null if there is no parent * shell */ Shell::Pointer GetParentShell(); /** * Returns a shell listener. This shell listener gets registered with this * window's shell. *

* The default implementation of this framework method returns a new * listener that makes this window the active window for its window manager * (if it has one) when the shell is activated, and calls the framework * method handleShellCloseEvent when the shell is closed. * Subclasses may extend or reimplement. *

* * @return a shell listener */ virtual IShellListener* GetShellListener(); /** * Returns the shell style bits. *

* The default value is SWT.CLOSE|SWT.MIN|SWT.MAX|SWT.RESIZE. * Subclassers should call setShellStyle to change this * value, rather than overriding this method. *

* * @return the shell style bits */ int GetShellStyle(); /** * Notifies that the window's close button was pressed, the close menu was * selected, or the ESCAPE key pressed. *

* The default implementation of this framework method sets the window's * return code to CANCEL and closes the window using * close. Subclasses may extend or reimplement. *

*/ virtual void HandleShellCloseEvent(); /** * Initializes the location and size of this window's SWT shell after it has * been created. *

* This framework method is called by the create framework * method. The default implementation calls getInitialSize * and getInitialLocation and passes the results to * Shell.setBounds. This is only done if the bounds of the * shell have not already been modified. Subclasses may extend or * reimplement. *

*/ virtual void InitializeBounds(); /** * Changes the parent shell. This is only safe to use when the shell is not * yet realized (i.e., created). Once the shell is created, it must be * disposed (i.e., closed) before this method can be called. * * @param newParentShell * The new parent shell; this value may be null if * there is to be no parent. * @since 3.1 */ void SetParentShell(Shell::Pointer newParentShell); /** * Sets this window's return code. The return code is automatically returned * by open if block on open is enabled. For non-blocking * opens, the return code needs to be retrieved manually using * getReturnCode. * * @param code * the return code */ void SetReturnCode(int code); /** * Sets the shell style bits. This method has no effect after the shell is * created. *

* The shell style bits are used by the framework method * createShell when creating this window's shell. *

* * @param newShellStyle * the new shell style bits */ void SetShellStyle(int newShellStyle); /** * Configures this window to have a menu bar. * Does nothing if it already has one. * This method must be called before this window's shell is created. */ void AddMenuBar(); /** * Returns a new menu manager for the window. *

* Subclasses may override this method to customize the menu manager. *

* @return a menu manager */ virtual SmartPointer CreateMenuManager(); /** * Creates the trim widgets around the content area. * * @param shell the shell */ virtual void CreateTrimWidgets(SmartPointer shell); public: /** * Closes this window, disposes its shell, and removes this window from its * window manager (if it has one). *

* This framework method may be extended (super.close must * be called). *

*

* Note that in order to prevent recursive calls to this method * it does not call Shell#close(). As a result ShellListeners * will not receive a shellClosed event. *

* * @return true if the window is (or was already) closed, and * false if it is still open */ virtual bool Close(); /** * Creates this window's widgetry in a new top-level shell. *

* The default implementation of this framework method creates this window's * shell (by calling createShell), and its controls (by * calling createContents), then initializes this window's * shell bounds (by calling initializeBounds). *

*/ virtual void Create(); /** * Returns the default image. This is the image that will be used for * windows that have no shell image at the time they are opened. There is no * default image unless one is installed via setDefaultImage. * * @return the default image, or null if none * @see #setDefaultImage */ static void* GetDefaultImage(); /** * Returns the array of default images to use for newly opened windows. It * is expected that the array will contain the same icon rendered at * different resolutions. * * @see org.blueberry.swt.widgets.Decorations#setImages(org.blueberry.swt.graphics.Image[]) * * @return the array of images to be used when a new window is opened * @see #setDefaultImages * @since 3.0 */ static QList GetDefaultImages(); /** * Returns this window's return code. A window's return codes are * window-specific, although two standard return codes are predefined: * OK and CANCEL. * * @return the return code */ int GetReturnCode(); /** * Returns this window's shell. * * @return this window's shell, or null if this window's * shell has not been created yet */ Shell::Pointer GetShell() const; /** * Returns the window manager of this window. * * @return the WindowManager, or null if none */ WindowManager* GetWindowManager(); /** * Returns the menu bar manager for this window (if it has one). * * @return the menu bar manager, or null if * this window does not have a menu bar * @see #addMenuBar() */ MenuManager* GetMenuBarManager() const; /** * Opens this window, creating it first if it has not yet been created. *

* If this window has been configured to block on open ( * setBlockOnOpen), this method waits until the window is * closed by the end user, and then it returns the window's return code; * otherwise, this method returns immediately. A window's return codes are * window-specific, although two standard return codes are predefined: * OK and CANCEL. *

* * @return the return code * * @see #create() */ int Open(); /** * Sets whether the open method should block until the window * closes. * * @param shouldBlock * true if the open method should * not return until the window closes, and false * if the open method should return immediately */ void SetBlockOnOpen(bool shouldBlock); /** * Sets the default image. This is the image that will be used for windows * that have no shell image at the time they are opened. There is no default * image unless one is installed via this method. * * @param image * the default image, or null if none */ static void SetDefaultImage(void* image); /** * Sets the array of default images to use for newly opened windows. It is * expected that the array will contain the same icon rendered at different * resolutions. * * @see org.blueberry.swt.widgets.Decorations#setImages(org.blueberry.swt.graphics.Image[]) * * @param images * the array of images to be used when this window is opened * @since 3.0 */ static void SetDefaultImages(const QList& images); /** * Sets the window manager of this window. *

* Note that this method is used by WindowManager to maintain * a backpointer. Clients must not call the method directly. *

* * @param manager * the window manager, or null if none */ void SetWindowManager(WindowManager* manager); /** * Sets the exception handler for this application. *

* Note that the handler may only be set once. Subsequent calls to this method will be * ignored. *

* * @param handler * the exception handler for the application. */ static void SetExceptionHandler(IExceptionHandler::Pointer handler); /** * Sets the default parent for modal Windows. This will be used to locate * the parent for any modal Window constructed with a null parent. * * @param provider shell provider that will be used to locate the parent shell * whenever a Window is created with a null parent * @since 3.1 */ static void SetDefaultModalParent(IShellProvider::Pointer provider); }; } #endif /* BERRYWINDOW_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.h index ba0eae4ede..05157ffc58 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.h @@ -1,55 +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. ===================================================================*/ #ifndef BERRYGUITKCONTROLEVENT_H_ #define BERRYGUITKCONTROLEVENT_H_ #include "berryGuiTkEvent.h" namespace berry { namespace GuiTk { /** * Instances of this class are sent as a result of * controls being moved or resized. * * @see ControlListener * @see Sample code and further information */ class BERRY_UI_QT ControlEvent: public Event { public: - berryObjectMacro(ControlEvent); + berryObjectMacro(ControlEvent) ControlEvent(); ControlEvent(void* item, int x = 0, int y = 0, int width = 0, int height = 0); }; } } #endif /* BERRYGUITKCONTROLEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractDropTarget.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractDropTarget.h index cae66c62d9..67381778bd 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractDropTarget.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractDropTarget.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 BERRYABSTRACTDROPTARGET_H_ #define BERRYABSTRACTDROPTARGET_H_ #include "berryIDropTarget.h" namespace berry { struct AbstractDropTarget : public IDropTarget { /* * @see IDropTarget#GetSnapRectangle() */ - Rectangle GetSnapRectangle() + QRect GetSnapRectangle() { - return Rectangle(); + return QRect(); } void DragFinished(bool /*dropPerformed*/) { } }; } #endif /* BERRYABSTRACTDROPTARGET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.cpp index d9283f1ccb..c326b63c8b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.cpp @@ -1,113 +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 "berryDefaultStackPresentationSite.h" namespace berry { DefaultStackPresentationSite::DefaultStackPresentationSite() : state(IStackPresentationSite::STATE_RESTORED), activeState(StackPresentation::AS_INACTIVE) {} void DefaultStackPresentationSite::SetPresentation(StackPresentation::Pointer newPresentation) { presentation = newPresentation; if (presentation != 0) { presentation->SetState(state); presentation->SetActive(activeState); } } StackPresentation::Pointer DefaultStackPresentationSite::GetPresentation() { return presentation; } int DefaultStackPresentationSite::GetState() { return state; } void DefaultStackPresentationSite::SetActive(int activeState) { if (activeState != this->activeState) { this->activeState = activeState; if (presentation != 0) { presentation->SetActive(activeState); } } } int DefaultStackPresentationSite::GetActive() { return activeState; } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IStackPresentationSite#selectPart(org.blueberry.ui.internal.skins.IPresentablePart) */ void DefaultStackPresentationSite::SelectPart(IPresentablePart::Pointer toSelect) { if (presentation != 0) { presentation->SelectPart(toSelect); } } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#setState(int) */ void DefaultStackPresentationSite::SetState(int newState) { this->SetPresentationState(newState); } void DefaultStackPresentationSite::SetPresentationState(int newState) { state = newState; if (presentation != 0) { presentation->SetState(newState); } } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentablePart#isClosable() */ bool DefaultStackPresentationSite::IsCloseable(IPresentablePart::Pointer part) { return part->IsCloseable(); } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(org.blueberry.ui.internal.skins.IPresentablePart, boolean) */ - void DefaultStackPresentationSite::DragStart(IPresentablePart::Pointer /*beingDragged*/, Point& /*initialPosition*/, + void DefaultStackPresentationSite::DragStart(IPresentablePart::Pointer /*beingDragged*/, QPoint& /*initialPosition*/, bool /*keyboard*/) { } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#close(org.blueberry.ui.internal.skins.IPresentablePart) */ void DefaultStackPresentationSite::Close(IPresentablePart::Pointer /*toClose*/) { } /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(boolean) */ - void DefaultStackPresentationSite::DragStart(Point& /*initialPosition*/, bool /*keyboard*/) { + void DefaultStackPresentationSite::DragStart(QPoint& /*initialPosition*/, bool /*keyboard*/) { } /* (non-Javadoc) * @see org.blueberry.ui.presentations.IStackPresentationSite#supportsState(int) */ bool DefaultStackPresentationSite::SupportsState(int /*state*/) { return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h index bb32abdfac..ee7ea5b0c6 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h @@ -1,101 +1,101 @@ /*=================================================================== 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 BERRYDEFAULTSTACKPRESENTATIONSITE_H_ #define BERRYDEFAULTSTACKPRESENTATIONSITE_H_ #include "presentations/berryIStackPresentationSite.h" #include "presentations/berryStackPresentation.h" namespace berry { class DefaultStackPresentationSite: public IStackPresentationSite { private: StackPresentation::Pointer presentation; int state; int activeState; public: berryObjectMacro(DefaultStackPresentationSite) DefaultStackPresentationSite(); void SetPresentation(StackPresentation::Pointer newPresentation); StackPresentation::Pointer GetPresentation(); int GetState(); void SetActive(int activeState); int GetActive(); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IStackPresentationSite#selectPart(org.blueberry.ui.internal.skins.IPresentablePart) */ void SelectPart(IPresentablePart::Pointer toSelect); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#setState(int) */ void SetState(int newState); void SetPresentationState(int newState); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentablePart#isClosable() */ bool IsCloseable(IPresentablePart::Pointer part); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(org.blueberry.ui.internal.skins.IPresentablePart, boolean) */ void DragStart(IPresentablePart::Pointer beingDragged, - Point& initialPosition, bool keyboard); + QPoint& initialPosition, bool keyboard); using IStackPresentationSite::Close; /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#close(org.blueberry.ui.internal.skins.IPresentablePart) */ void Close(IPresentablePart::Pointer toClose); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(boolean) */ - void DragStart(Point& initialPosition, bool keyboard); + void DragStart(QPoint& initialPosition, bool keyboard); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IStackPresentationSite#supportsState(int) */ bool SupportsState(int state); // void AddSystemActions(IMenuManager menuManager) { // // } }; } #endif /* BERRYDEFAULTSTACKPRESENTATIONSITE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp index 3afc3ee7dd..6632e297aa 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp @@ -1,146 +1,146 @@ /*=================================================================== 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 "berryDetachedPlaceHolder.h" #include "berryILayoutContainer.h" #include "berryPartPlaceholder.h" #include "berryWorkbenchConstants.h" namespace berry { DetachedPlaceHolder::DetachedPlaceHolder(const QString& id, - const Rectangle& b) : + const QRect& b) : PartPlaceholder(id), bounds(b) { } void DetachedPlaceHolder::Add(LayoutPart::Pointer newPart) { if (newPart.Cast () == 0) { return; } children.push_back(newPart); } bool DetachedPlaceHolder::AllowsBorder() { return false; } bool DetachedPlaceHolder::AllowsAdd(LayoutPart::Pointer toAdd) { return PartPlaceholder::AllowsAdd(toAdd); } bool DetachedPlaceHolder::AllowsAutoFocus() { return PartPlaceholder::AllowsAutoFocus(); } -Rectangle DetachedPlaceHolder::GetBounds() +QRect DetachedPlaceHolder::GetBounds() { return bounds; } QList DetachedPlaceHolder::GetChildren() { return children; } void DetachedPlaceHolder::Remove(LayoutPart::Pointer part) { children.removeAll(part); } void DetachedPlaceHolder::Replace(LayoutPart::Pointer oldPart, LayoutPart::Pointer newPart) { this->Remove(oldPart); this->Add(newPart); } void DetachedPlaceHolder::RestoreState(IMemento::Pointer memento) { // Read the bounds. int x = 0; memento->GetInteger(WorkbenchConstants::TAG_X, x); int y = 0; memento->GetInteger(WorkbenchConstants::TAG_Y, y); int width = 0; memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width); int height = 0; memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height); - bounds = Rectangle(x, y, width, height); + bounds = QRect(x, y, width, height); // Restore the placeholders. QList childrenMem(memento ->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int i = 0; i < childrenMem.size(); i++) { QString id; childrenMem[i]->GetString(WorkbenchConstants::TAG_ID, id); PartPlaceholder::Pointer holder(new PartPlaceholder(id)); holder->SetContainer(ILayoutContainer::Pointer(this)); children.push_back(holder); } } void DetachedPlaceHolder::SaveState(IMemento::Pointer memento) { // Save the bounds. - memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x); - memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); - memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); - memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); + memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x()); + memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y()); + memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width()); + memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height()); // Save the views. for (QList::iterator i = children.begin(); i != children.end(); ++i) { IMemento::Pointer childMem = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); childMem->PutString(WorkbenchConstants::TAG_ID, (*i)->GetID()); } } void DetachedPlaceHolder::FindSashes(LayoutPart::Pointer /*part*/, PartPane::Sashes& sashes) { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } ILayoutContainer::ChildrenType DetachedPlaceHolder::GetChildren() const { return children; } void DetachedPlaceHolder::ResizeChild(LayoutPart::Pointer childThatChanged) { PartPlaceholder::ResizeChild(childThatChanged); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.h index bf64ef3cee..5640a20a73 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.h @@ -1,112 +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. ===================================================================*/ #ifndef BERRYDETACHEDPLACEHOLDER_H_ #define BERRYDETACHEDPLACEHOLDER_H_ #include "berryPartPlaceholder.h" #include "berryILayoutContainer.h" #include "berryIMemento.h" -#include "berryRectangle.h" - -#include namespace berry { /** * DetachedPlaceHolder is the placeholder for detached views. * */ class DetachedPlaceHolder : public PartPlaceholder, public ILayoutContainer { private: QList children; - Rectangle bounds; + QRect bounds; public: berryObjectMacro(DetachedPlaceHolder) /** * DetachedPlaceHolder constructor comment. * @param id java.lang.String * @param bounds the size of the placeholder */ - DetachedPlaceHolder(const QString& id, const Rectangle& b); + DetachedPlaceHolder(const QString& id, const QRect& b); /** * Add a child to the container. */ void Add(LayoutPart::Pointer newPart); /** * Return true if the container allows its * parts to show a border if they choose to, * else false if the container does not want * its parts to show a border. * @return boolean */ bool AllowsBorder(); bool AllowsAdd(LayoutPart::Pointer toAdd); bool AllowsAutoFocus(); - Rectangle GetBounds(); + QRect GetBounds(); /** * Returns a list of layout children. */ QList GetChildren(); /** * Remove a child from the container. */ void Remove(LayoutPart::Pointer part); /** * Replace one child with another */ void Replace(LayoutPart::Pointer oldPart, LayoutPart::Pointer newPart); /** * Restore the state from the memento. * @param memento */ void RestoreState(IMemento::Pointer memento); /** * Save state to the memento. * @param memento */ void SaveState(IMemento::Pointer memento); void FindSashes(LayoutPart::Pointer part, PartPane::Sashes& sashes); ILayoutContainer::ChildrenType GetChildren() const; void ResizeChild(LayoutPart::Pointer childThatChanged); }; } #endif /* BERRYDETACHEDPLACEHOLDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp index 58084a7f33..bf970afb08 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp @@ -1,540 +1,540 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryDetachedWindow.h" #include "berryIWorkbenchPartConstants.h" #include "berryISaveablePart.h" #include "berryWorkbenchWindow.h" #include "berryWorkbenchConstants.h" #include "berryEditorManager.h" #include "berryDragUtil.h" namespace berry { DetachedWindow::ShellListener::ShellListener(DetachedWindow* wnd) : window(wnd) { } void DetachedWindow::ShellListener::ShellClosed(const ShellEvent::Pointer& e) { // hold on to a reference of the DetachedWindow instance // (otherwise, wnd->HandleClose() woulde delete the DetachedWindow // instance too early, trying to write to members afterwards) DetachedWindow::Pointer wnd(window); // only continue to close if the handleClose // wasn't canceled e->doit = wnd->HandleClose(); } DetachedWindow::ShellControlListener::ShellControlListener(DetachedWindow* wnd) : window(wnd) { } GuiTk::IControlListener::Events::Types DetachedWindow::ShellControlListener::GetEventTypes() const { return Events::RESIZED; } void DetachedWindow::ShellControlListener::ControlResized( GuiTk::ControlEvent::Pointer e) { window->folder->SetBounds( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(e->item)); } DetachedWindow::DetachedWindow(WorkbenchPage* workbenchPage) : folder(new PartStack(workbenchPage, false)) , page(workbenchPage) , hideViewsOnClose(true) , shellListener(new ShellListener(this)) , resizeListener(new ShellControlListener(this)) { } void DetachedWindow::PropertyChange(const Object::Pointer& /*source*/, int propId) { if (propId == IWorkbenchPartConstants::PROP_TITLE) { this->UpdateTitle(); } else if (propId == PartStack::PROP_SELECTION) { this->ActivePartChanged(this->GetPartReference(folder->GetSelection())); } } Shell::Pointer DetachedWindow::GetShell() { return windowShell; } void DetachedWindow::Create() { folder->AddListener(this); windowShell = page->GetWorkbenchWindow().Cast () ->GetDetachedWindowPool()->AllocateShell( shellListener.data()); windowShell->SetData(Object::Pointer(this)); windowShell->SetText(""); DragUtil::AddDragTarget(windowShell->GetControl(), this); hideViewsOnClose = true; - if (bounds.IsEmpty()) + if (bounds.isEmpty()) { - Rectangle windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds(); - Point center(windowRect.x + windowRect.width / 2, windowRect.y - - windowRect.height / 2); - bounds = Rectangle(center.x - 150, center.y + 100, 300, 200); + QRect windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds(); + QPoint center(windowRect.x() + windowRect.width() / 2, windowRect.y() + - windowRect.height() / 2); + bounds = QRect(center.x() - 150, center.y() + 100, 300, 200); } // Force the rect into the current display - Rectangle dispBounds = + QRect dispBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize(); - if (bounds.width > dispBounds.width) - bounds.width = dispBounds.width; - if (bounds.height > dispBounds.height) - bounds.height = dispBounds.height; - if (bounds.x + bounds.width > dispBounds.width) - bounds.x = dispBounds.width - bounds.width; - if (bounds.y + bounds.height > dispBounds.height) - bounds.y = dispBounds.height - bounds.height; + if (bounds.width() > dispBounds.width()) + bounds.setWidth(dispBounds.width()); + if (bounds.height() > dispBounds.height()) + bounds.setHeight(dispBounds.height()); + if (bounds.x() + bounds.width() > dispBounds.width()) + bounds.setX(dispBounds.width() - bounds.width()); + if (bounds.y() + bounds.height() > dispBounds.height()) + bounds.setY(dispBounds.height() - bounds.height()); this->GetShell()->SetBounds(bounds); this->ConfigureShell(windowShell); this->CreateContents(windowShell->GetControl()); //windowShell->Layout(true); //folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(windowShell->GetControl())); } void DetachedWindow::Add(LayoutPart::Pointer part) { Shell::Pointer shell = this->GetShell(); if (shell != 0) { part->Reparent(shell->GetControl()); } folder->Add(part); this->UpdateMinimumSize(); } bool DetachedWindow::BelongsToWorkbenchPage( IWorkbenchPage::Pointer workbenchPage) { return (workbenchPage == this->page); } bool DetachedWindow::Close() { hideViewsOnClose = false; Shell::Pointer shell = this->GetShell(); if (shell != 0) { shell->Close(); } return true; } IDropTarget::Pointer DetachedWindow::Drag(void* /*currentControl*/, - const Object::Pointer& draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) + const Object::Pointer& draggedObject, const QPoint& position, const QRect& /*dragRectangle*/) { if (draggedObject.Cast () == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); if (sourcePart->GetWorkbenchWindow() != page->GetWorkbenchWindow()) { return IDropTarget::Pointer(0); } // Only handle the event if the source part is acceptable to the particular PartStack IDropTarget::Pointer target; if (folder->AllowsDrop(sourcePart)) { target = folder->GetDropTarget(draggedObject, position); if (target == 0) { - Rectangle displayBounds = + QRect displayBounds = DragUtil::GetDisplayBounds(folder->GetControl()); - if (displayBounds.Contains(position)) + if (displayBounds.contains(position)) { StackDropResult::Pointer stackDropResult(new StackDropResult( displayBounds, Object::Pointer(0))); target = folder->CreateDropTarget(sourcePart, stackDropResult); } else { return IDropTarget::Pointer(0); } } } return target; } ILayoutContainer::ChildrenType DetachedWindow::GetChildren() const { return folder->GetChildren(); } WorkbenchPage::Pointer DetachedWindow::GetWorkbenchPage() { return WorkbenchPage::Pointer(this->page); } void DetachedWindow::RestoreState(IMemento::Pointer memento) { // Read the bounds. int x = 0; memento->GetInteger(WorkbenchConstants::TAG_X, x); int y = 0; memento->GetInteger(WorkbenchConstants::TAG_Y, y); int width = 0; memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width); int height = 0; memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height); // memento->GetInteger(WorkbenchConstants::TAG_FLOAT); // Set the bounds. - bounds = Rectangle(x, y, width, height); + bounds = QRect(x, y, width, height); if (GetShell()) { GetShell()->SetBounds(bounds); } // Create the folder. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_FOLDER); if (childMem) { folder->RestoreState(childMem); } } void DetachedWindow::SaveState(IMemento::Pointer memento) { if (GetShell()) { bounds = GetShell()->GetBounds(); } // Save the bounds. - memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x); - memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); - memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); - memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); + memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x()); + memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y()); + memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width()); + memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height()); // Save the views. IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_FOLDER); folder->SaveState(childMem); } void* DetachedWindow::GetControl() { return folder->GetControl(); } int DetachedWindow::Open() { if (this->GetShell() == 0) { this->Create(); } - Rectangle bounds = this->GetShell()->GetBounds(); + QRect bounds = this->GetShell()->GetBounds(); if (!(bounds == this->GetShell()->GetBounds())) { this->GetShell()->SetBounds(bounds); } this->GetShell()->SetVisible(true); folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(this->GetShell()->GetControl())); return 0; } void DetachedWindow::ActivePartChanged( IWorkbenchPartReference::Pointer partReference) { if (activePart == partReference) { return; } if (activePart != 0) { activePart->RemovePropertyListener(this); } activePart = partReference; if (partReference != 0) { partReference->AddPropertyListener(this); } this->UpdateTitle(); } void DetachedWindow::ConfigureShell(Shell::Pointer shell) { this->UpdateTitle(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener( shell->GetControl(), resizeListener); //shell.addListener(SWT.Activate, activationListener); //shell.addListener(SWT.Deactivate, activationListener); //TODO DetachedWindow key bindings // // Register this detached view as a window (for key bindings). // IContextService contextService = (IContextService) getWorkbenchPage() // .getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); // // page.getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.DETACHED_WINDOW); } void* DetachedWindow::CreateContents(void* parent) { // Create the tab folder. folder->CreateControl(parent); // Reparent each view in the tab folder. QList detachedChildren; this->CollectViewPanes(detachedChildren, this->GetChildren()); for (QList::iterator itr = detachedChildren.begin(); itr != detachedChildren.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } //TODO DetachedWindow listen to folder events (update size?) // if (folder->GetPresentation() // instanceof TabbedStackPresentation) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // AbstractTabFolder tabFolder = stack.getTabFolder(); // tabFolder.addListener(new TabFolderListener() // { // public void handleEvent(TabFolderEvent e) // { // switch (e.type) // { // case TabFolderEvent.EVENT_CLOSE: // { // updateMinimumSize(); // break; // } // case TabFolderEvent.EVENT_PREFERRED_SIZE: // { // updateMinimumSize(); // break; // } // } // } // }); // } // Return tab folder control. return folder->GetControl(); } void DetachedWindow::UpdateTitle() { if (activePart != 0) { // Uncomment to set the shell title to match the title of the active part // String text = activePart.getTitle(); // // if (!text.equals(s.getText())) { // s.setText(text); // } } } void DetachedWindow::UpdateMinimumSize() { // // We can only do this for 'Tabbed' stacked presentations. // if (folder.getPresentation().Cast() != 0) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // // if (stack->GetPartList().size() == 1) // { // // Get the minimum space required for the part // int width = stack->ComputePreferredSize(true, Constants::INF, Constants::INF, 0); // int height = stack->ComputePreferredSize(false, Constants::INF, Constants::INF, 0); // // // Take the current shell 'trim' into account // int shellHeight = windowShell->GetBounds().height - windowShell->GetClientArea().height; // int shellWidth = windowShell->GetBounds().width - windowShell->GetClientArea().width; // // windowShell->SetMinimumSize(width + shellWidth, height + shellHeight); // } // } } IWorkbenchPartReference::Pointer DetachedWindow::GetPartReference( LayoutPart::Pointer pane) { if (pane == 0 || pane.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } return pane.Cast ()->GetPartReference(); } bool DetachedWindow::HandleClose() { if (hideViewsOnClose) { QList views; this->CollectViewPanes(views, this->GetChildren()); // Save any dirty views if (!this->HandleSaves(views)) { return false; // User canceled the save } // OK, go on with the closing for (QList::iterator itr = views.begin(); itr != views.end(); ++itr) { PartPane::Pointer child = *itr; // Only close if closable... if (child->IsCloseable()) { page->HideView(child->GetPartReference().Cast ()); // Was the close cancelled? if (child->GetContainer() != 0) return false; } else { page->AttachView(child->GetPartReference().Cast ()); } } } if (folder != 0) { folder->Dispose(); } if (windowShell != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener( windowShell->GetControl(), resizeListener); // windowShell.removeListener(SWT.Activate, activationListener); // windowShell.removeListener(SWT.Deactivate, activationListener); DragUtil::RemoveDragTarget(windowShell->GetControl(), this); bounds = windowShell->GetBounds(); //TODO DetachedWindow unregister key bindings // // Unregister this detached view as a window (for key bindings). // final IContextService contextService = (IContextService) getWorkbenchPage().getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.unregisterShell(windowShell); windowShell->SetData(Object::Pointer(0)); windowShell = 0; } return true; } bool DetachedWindow::HandleSaves(QList views) { QList dirtyViews; for (QList::iterator iterator = views.begin(); iterator != views.end(); ++iterator) { PartPane::Pointer pane = *iterator; IViewReference::Pointer ref = pane->GetPartReference().Cast (); IViewPart::Pointer part = ref->GetView(false); if (part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty() && saveable->IsSaveOnCloseNeeded()) { dirtyViews.push_back(part); } } } // If there are any prompt to save -before- any closing happens // FIXME: This code will result in a double prompt if the user // decides not to save a particular view at this stage they'll // get a second one from the 'hideView' call... if (dirtyViews.size() > 0) { IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow(); bool success = EditorManager::SaveAll(dirtyViews, true, true, false, window); if (!success) { return false; // the user canceled. } } return true; } void DetachedWindow::CollectViewPanes(QList& result, const QList& parts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { result.push_back(part.Cast ()); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h index 938c7e4357..51ecbf4e31 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h @@ -1,197 +1,196 @@ /*=================================================================== 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 BERRYDETACHEDWINDOW_H_ #define BERRYDETACHEDWINDOW_H_ #include "berryPartStack.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryIDragOverListener.h" #include "berryIShellListener.h" #include "guitk/berryGuiTkIControlListener.h" -#include "berryRectangle.h" #include "berryShell.h" namespace berry { /** * TODO: Drag from detached to fast view bar back to detached causes NPE */ class DetachedWindow: public Object, private IPropertyChangeListener, private IDragOverListener { public: berryObjectMacro(DetachedWindow) private: PartStack::Pointer folder; WorkbenchPage* page; - Rectangle bounds; + QRect bounds; Shell::Pointer windowShell; bool hideViewsOnClose; struct ShellListener: public IShellListener { ShellListener(DetachedWindow* wnd); void ShellClosed(const ShellEvent::Pointer& e); private: DetachedWindow* window; }; QScopedPointer shellListener; struct ShellControlListener: public GuiTk::IControlListener { ShellControlListener(DetachedWindow* wnd); Events::Types GetEventTypes() const; void ControlResized(GuiTk::ControlEvent::Pointer e); private: DetachedWindow* window; }; GuiTk::IControlListener::Pointer resizeListener; // Listener activationListener = new Listener() { // public void handleEvent(Event event) { // switch (event.type) { // case SWT.Activate: // page.window.liftRestrictions(); // break; // case SWT.Deactivate: // page.window.imposeRestrictions(); // break; // } // } // }; IWorkbenchPartReference::Pointer activePart; public: /** * Create a new FloatingWindow. */ DetachedWindow(WorkbenchPage* workbenchPage); using IPropertyChangeListener::PropertyChange; void PropertyChange(const Object::Pointer& source, int propId); Shell::Pointer GetShell(); void Create(); /** * Adds a visual part to this window. * Supports reparenting. */ void Add(LayoutPart::Pointer part); bool BelongsToWorkbenchPage(IWorkbenchPage::Pointer workbenchPage); bool Close(); /* - * @see org.blueberry.ui.internal.IDragOverListener#Drag(void*, Object::Pointer, const Point&, const Rectangle& ) + * @see org.blueberry.ui.internal.IDragOverListener#Drag(void*, Object::Pointer, const QPoint&, const QRect& ) */ IDropTarget::Pointer Drag(void* currentControl, - const Object::Pointer& draggedObject, const Point& position, - const Rectangle& dragRectangle); + const Object::Pointer& draggedObject, const QPoint& position, + const QRect& dragRectangle); ILayoutContainer::ChildrenType GetChildren() const; WorkbenchPage::Pointer GetWorkbenchPage(); /** * @see IPersistablePart */ void RestoreState(IMemento::Pointer memento); /** * @see IPersistablePart */ void SaveState(IMemento::Pointer memento); void* GetControl(); /** * Opens the detached window. */ int Open(); protected: void ActivePartChanged(IWorkbenchPartReference::Pointer partReference); /** * This method will be called to initialize the given Shell's layout */ void ConfigureShell(Shell::Pointer shell); /** * Override this method to create the widget tree that is used as the window's contents. */ void* CreateContents(void* parent); private: void UpdateTitle(); /** * Ensure that the shell's minimum size is equal to the minimum size * of the first part added to the shell. */ void UpdateMinimumSize(); static IWorkbenchPartReference::Pointer GetPartReference( LayoutPart::Pointer pane); /** * Closes this window and disposes its shell. */ bool HandleClose(); /** * Prompts for and handles the saving of dirty, saveable views * @param views The list of ViewPanes * @return true unless the user cancels the save(s) */ bool HandleSaves(QList views); /** * Answer a list of the view panes. */ void CollectViewPanes(QList& result, const QList& parts); }; } #endif /* BERRYDETACHEDWINDOW_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp index 6960e0ec7b..5b8cb5afa9 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp @@ -1,362 +1,361 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryDragUtil.h" #include "berryGeometry.h" -#include "tweaklets/berryDnDTweaklet.h" -#include "tweaklets/berryITracker.h" +#include "berryQtTracker.h" namespace berry { const QString DragUtil::DROP_TARGET_ID = "org.blueberry.ui.internal.dropTarget"; TestDropLocation::Pointer DragUtil::forcedDropTarget(0); QList DragUtil::defaultTargets = QList(); DragUtil::TrackerMoveListener::TrackerMoveListener(Object::Pointer draggedItem, - const Rectangle& sourceBounds, const Point& initialLocation, + const QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping) : allowSnapping(allowSnapping), draggedItem(draggedItem), sourceBounds( sourceBounds), initialLocation(initialLocation) { } GuiTk::IControlListener::Events::Types DragUtil::TrackerMoveListener::GetEventTypes() const { return Events::MOVED; } void DragUtil::TrackerMoveListener::ControlMoved( GuiTk::ControlEvent::Pointer event) { // Get the curslor location as a point - Point location(event->x, event->y); + QPoint location(event->x, event->y); // Select a drop target; use the global one by default IDropTarget::Pointer target; void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); - // Get the ITracker which fired the event - ITracker* tracker = static_cast (event->item); + // Get the QtTracker which fired the event + QtTracker* tracker = static_cast (event->item); // Get the drop target for this location target = DragUtil::GetDropTarget(targetControl, draggedItem, location, tracker->GetRectangle()); // Set up the tracker feedback based on the target - Rectangle snapTarget; + QRect snapTarget; if (target != 0) { snapTarget = target->GetSnapRectangle(); tracker->SetCursor(target->GetCursor()); } else { - tracker->SetCursor(DnDTweaklet::CURSOR_INVALID); + tracker->SetCursor(CURSOR_INVALID); } // If snapping then reset the tracker's rectangle based on the current drop target if (allowSnapping) { - if (snapTarget.width == 0 || snapTarget.height == 0) + if (snapTarget.width() < 0 || snapTarget.height() < 0) { - snapTarget = Rectangle(sourceBounds.x + location.x - initialLocation.x, - sourceBounds.y + location.y - initialLocation.y, sourceBounds.width, - sourceBounds.height); + snapTarget = QRect(sourceBounds.x() + location.x() - initialLocation.x(), + sourceBounds.y() + location.y() - initialLocation.y(), sourceBounds.width(), + sourceBounds.height()); } // Try to prevent flicker: don't change the rectangles if they're already in // the right location - Rectangle currentRectangle = tracker->GetRectangle(); + QRect currentRectangle = tracker->GetRectangle(); if (!(currentRectangle == snapTarget)) { tracker->SetRectangle(snapTarget); } } } DragUtil::TargetListType::Pointer DragUtil::GetTargetList(void* control) { Object::Pointer data = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetData( control, DROP_TARGET_ID); TargetListType::Pointer list = data.Cast (); return list; } IDropTarget::Pointer DragUtil::GetDropTarget(const QList& toSearch, void* mostSpecificControl, Object::Pointer draggedObject, - const Point& position, - const Rectangle& dragRectangle) + const QPoint& position, + const QRect& dragRectangle) { for (QList::const_iterator iter = toSearch.begin(); iter != toSearch.end(); ++iter) { IDragOverListener* next = *iter; IDropTarget::Pointer dropTarget = next->Drag(mostSpecificControl, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } } return IDropTarget::Pointer(0); } void DragUtil::AddDragTarget(void* control, IDragOverListener* target) { if (control == 0) { defaultTargets.push_back(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList == 0) { targetList = new TargetListType(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, targetList); } targetList->push_back(target); } } void DragUtil::RemoveDragTarget(void* control, IDragOverListener* target) { if (control == 0) { defaultTargets.removeAll(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList != 0) { targetList->removeAll(target); if (targetList->empty()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, Object::Pointer(0)); } } } } -Rectangle DragUtil::GetDisplayBounds(void* boundsControl) +QRect DragUtil::GetDisplayBounds(void* boundsControl) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent( boundsControl); if (parent == 0) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(boundsControl); } - Rectangle rect = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds( + QRect rect = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds( boundsControl); return Geometry::ToDisplay(parent, rect); } bool DragUtil::PerformDrag(Object::Pointer draggedItem, - const Rectangle& sourceBounds, const Point& initialLocation, + const QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping) { IDropTarget::Pointer target = DragToTarget(draggedItem, sourceBounds, initialLocation, allowSnapping); if (target == 0) { return false; } target->Drop(); target->DragFinished(true); return true; } void DragUtil::ForceDropLocation(TestDropLocation::Pointer forcedLocation) { forcedDropTarget = forcedLocation; } IDropTarget::Pointer DragUtil::DragToTarget(Object::Pointer draggedItem, - const Rectangle& sourceBounds, const Point& initialLocation, + const QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping) { //final Display display = Display.getCurrent(); // Testing...immediately 'drop' onto the test target if (forcedDropTarget != 0) { - Point location = forcedDropTarget->GetLocation(); + QPoint location = forcedDropTarget->GetLocation(); void* currentControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->FindControl( forcedDropTarget->GetShells(), location); return GetDropTarget(currentControl, draggedItem, location, sourceBounds); } // Create a tracker. This is just an XOR rect on the screen. // As it moves we notify the drag listeners. - ITracker* tracker = Tweaklets::Get(DnDTweaklet::KEY)->CreateTracker(); + QtTracker tracker; //tracker.setStippled(true); GuiTk::IControlListener::Pointer trackerListener(new TrackerMoveListener( draggedItem, sourceBounds, initialLocation, allowSnapping)); - tracker->AddControlListener(trackerListener); + tracker.AddControlListener(trackerListener); // Setup...when the drag starts we might already be over a valid target, check this... // If there is a 'global' target then skip the check IDropTarget::Pointer target; void* startControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); if (startControl != 0 && allowSnapping) { target = GetDropTarget(startControl, draggedItem, initialLocation, sourceBounds); } // Set up an initial tracker rectangle - Rectangle startRect = sourceBounds; + QRect startRect = sourceBounds; if (target != 0) { - Rectangle rect = target->GetSnapRectangle(); + QRect rect = target->GetSnapRectangle(); - if (rect.width != 0 && rect.height != 0) + if (rect.width() != 0 && rect.height() != 0) { startRect = rect; } - tracker->SetCursor(target->GetCursor()); + tracker.SetCursor(target->GetCursor()); } - if (startRect.width != 0 && startRect.height != 0) + if (startRect.width() != 0 && startRect.height() != 0) { - tracker->SetRectangle(startRect); + tracker.SetRectangle(startRect); } // Tracking Loop...tracking is preformed on the 'SWT.Move' listener registered // against the tracker. // // HACK: // // Some control needs to capture the mouse during the drag or other // // controls will interfere with the cursor // Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); // if (shell != null) // { // shell.setCapture(true); // } // Run tracker until mouse up occurs or escape key pressed. - bool trackingOk = tracker->Open(); + bool trackingOk = tracker.Open(); // // HACK: // // Release the mouse now // if (shell != null) // { // shell.setCapture(false); // } // Done tracking... // Get the current drop target IDropTarget::Pointer dropTarget; - Point finalLocation = + QPoint finalLocation = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorLocation(); void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); dropTarget = GetDropTarget(targetControl, draggedItem, finalLocation, - tracker->GetRectangle()); + tracker.GetRectangle()); // Cleanup... - delete tracker; + //delete tracker; // if we're going to perform a 'drop' then delay the issuing of the 'finished' // callback until after it's done... if (trackingOk) { return dropTarget; } else if (dropTarget != 0) { // If the target can handle a 'finished' notification then send one dropTarget->DragFinished(false); } return IDropTarget::Pointer(0); } IDropTarget::Pointer DragUtil::GetDropTarget(void* toSearch, - Object::Pointer draggedObject, const Point& position, - const Rectangle& dragRectangle) + Object::Pointer draggedObject, const QPoint& position, + const QRect& dragRectangle) { // Search for a listener by walking the control's parent hierarchy for (void* current = toSearch; current != 0; current = Tweaklets::Get( GuiWidgetsTweaklet::KEY)->GetParent(current)) { TargetListType::Pointer targetList = GetTargetList(current); QList targets; if (targetList != 0) targets = *targetList; IDropTarget::Pointer dropTarget = GetDropTarget(targets, toSearch, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } // // Don't look to parent shells for drop targets // if (current instanceof Shell) { // break; // } } // No controls could handle this event -- check for default targets return GetDropTarget(defaultTargets, toSearch, draggedObject, position, dragRectangle); } -//Point DragUtil::GetEventLoc(GuiTk::ControlEvent::Pointer event) +//QPoint DragUtil::GetEventLoc(GuiTk::ControlEvent::Pointer event) //{ // Control ctrl = (Control) event.widget; -// return ctrl.toDisplay(new Point(event.x, event.y)); +// return ctrl.toDisplay(new QPoint(event.x, event.y)); //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h index 02ae03ceed..4df7ba7b62 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h @@ -1,214 +1,215 @@ /*=================================================================== 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 BERRYDRAGUTIL_H_ #define BERRYDRAGUTIL_H_ #include -#include "berryRectangle.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryTestDropLocation.h" #include "berryIDragOverListener.h" #include "berryIDropTarget.h" #include -#include + +#include +#include namespace berry { /** * Provides the methods for attaching drag-and-drop listeners to SWT controls. */ class BERRY_UI_QT DragUtil { public: typedef ObjectList TargetListType; private: static const QString DROP_TARGET_ID; /** * The location where all drags will end. If this is non-null, then * all user input is ignored in drag/drop. If null, we use user input * to determine where objects should be dropped. */ static TestDropLocation::Pointer forcedDropTarget; /** * List of IDragOverListener */ static QList defaultTargets; /** * Return the list of 'IDragOverListener' elements associated with * the given control. If there's a 'global' listener then always * return it. * * @param control * @return */ static TargetListType::Pointer GetTargetList(void* control); /** * Given a list of IDragOverListeners and a description of what is being dragged, it returns * a IDropTarget for the current drop. * * @param toSearch * @param mostSpecificControl * @param draggedObject * @param position * @param dragRectangle * @return */ static IDropTarget::Pointer GetDropTarget(const QList& toSearch, - void* mostSpecificControl, Object::Pointer draggedObject, const Point &position, - const Rectangle& dragRectangle); + void* mostSpecificControl, Object::Pointer draggedObject, const QPoint &position, + const QRect& dragRectangle); struct TrackerMoveListener : public GuiTk::IControlListener { - TrackerMoveListener(Object::Pointer draggedItem, const Rectangle& sourceBounds, - const Point& initialLocation, bool allowSnapping); + TrackerMoveListener(Object::Pointer draggedItem, const QRect& sourceBounds, + const QPoint& initialLocation, bool allowSnapping); Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer event); private: bool allowSnapping; Object::Pointer draggedItem; - Rectangle sourceBounds; - Point initialLocation; + QRect sourceBounds; + QPoint initialLocation; }; public: /** * Sets the drop target for the given control. It is possible to add one or more * targets for a "null" control. This becomes a default target that is used if no * other targets are found (for example, when dragging objects off the application * window). * * @param control the control that should be treated as a drag target, or null * to indicate the default target * @param target the drag target to handle the given control */ static void AddDragTarget(void* control, IDragOverListener* target); /** * Removes a drop target from the given control. * * @param control * @param target */ static void RemoveDragTarget(void* control, IDragOverListener* target); /** * Shorthand method. Returns the bounding rectangle for the given control, in * display coordinates. * * @param draggedItem * @param boundsControl * @return */ - static Rectangle GetDisplayBounds(void* boundsControl); + static QRect GetDisplayBounds(void* boundsControl); static bool PerformDrag(Object::Pointer draggedItem, - const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); + const QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping); // /** // * Drags the given item to the given location (in display coordinates). This // * method is intended for use by test suites. // * // * @param draggedItem object being dragged // * @param finalLocation location being dragged to // * @return true iff the drop was accepted // */ // static bool DragTo(Display display, Object draggedItem, -// Point finalLocation, Rectangle dragRectangle) { +// QPoint finalLocation, QRect dragRectangle) { // Control currentControl = SwtUtil.findControl(display, finalLocation); // // IDropTarget target = getDropTarget(currentControl, draggedItem, // finalLocation, dragRectangle); // // if (target == null) { // return false; // } // // target.drop(); // // return true; // } /** * Forces all drags to end at the given position (display coordinates). Intended * for use by test suites. If this method is called, then all subsequent calls * to performDrag will terminate immediately and behave as though the object were * dragged to the given location. Calling this method with null cancels this * behavior and causes performDrag to behave normally. * * @param forcedLocation location where objects will be dropped (or null to * cause drag/drop to behave normally). */ static void ForceDropLocation(TestDropLocation::Pointer forcedLocation); /** * Drags the given item, given an initial bounding rectangle in display coordinates. * Due to a quirk in the Tracker class, changing the tracking rectangle when using the * keyboard will also cause the mouse cursor to move. Since "snapping" causes the tracking * rectangle to change based on the position of the mouse cursor, it is impossible to do * drag-and-drop with the keyboard when snapping is enabled. * * @param draggedItem object being dragged * @param sourceBounds initial bounding rectangle for the dragged item * @param initialLocation initial position of the mouse cursor * @param allowSnapping true iff the rectangle should snap to the drop location. This must * be false if the user might be doing drag-and-drop using the keyboard. * * @return */ static IDropTarget::Pointer DragToTarget(Object::Pointer draggedItem, - const Rectangle& sourceBounds, const Point& initialLocation, + const QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping); /** * Returns the drag target for the given control or null if none. * * @param toSearch * @param e * @return */ static IDropTarget::Pointer GetDropTarget(void* toSearch, - Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle); + Object::Pointer draggedObject, const QPoint& position, const QRect& dragRectangle); /** * Returns the location of the given event, in display coordinates * @return */ - //static Point GetEventLoc(GuiTk::ControlEvent::Pointer event); + //static QPoint GetEventLoc(GuiTk::ControlEvent::Pointer event); }; } #endif /* BERRYDRAGUTIL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp index 132f5ce9a2..9ff0db04d8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp @@ -1,609 +1,609 @@ /*=================================================================== 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 "berryEditorSashContainer.h" #include "berryPresentationSerializer.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" #include "berryLayoutTree.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" #include "berryQtDnDControlWidget.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { const QString EditorSashContainer::DEFAULT_WORKBOOK_ID = "DefaultEditorWorkbook"; void EditorSashContainer::AddChild(const RelationshipInfo& info) { PartSashContainer::AddChild(info); this->UpdateStackButtons(); } void EditorSashContainer::ChildAdded(LayoutPart::Pointer child) { PartSashContainer::ChildAdded(child); if (child.Cast () != 0) { editorWorkbooks.push_back(child.Cast ()); } } void EditorSashContainer::ChildRemoved(LayoutPart::Pointer child) { PartSashContainer::ChildRemoved(child); if (child.Cast () != 0) { editorWorkbooks.removeAll(child.Cast()); if (activeEditorWorkbook == child) { this->SetActiveWorkbook(PartStack::Pointer(0), false); } this->UpdateStackButtons(); } } PartStack::Pointer EditorSashContainer::CreateDefaultWorkbook() { PartStack::Pointer newWorkbook = this->NewEditorWorkbook(); newWorkbook->SetID(DEFAULT_WORKBOOK_ID); this->Add(newWorkbook); return newWorkbook; } void EditorSashContainer::AddDropSupport() { WorkbenchWindowConfigurer::Pointer winConfigurer = page->GetWorkbenchWindow().Cast()->GetWindowConfigurer(); QtDnDControlWidget* dropWidget = static_cast(GetParent()); dropWidget->SetTransferTypes(winConfigurer->GetTransfers()); dropWidget->AddDropListener(winConfigurer->GetDropTargetListener()); } PartStack::Pointer EditorSashContainer::NewEditorWorkbook() { PartStack::Pointer newWorkbook(new PartStack(page, true, PresentationFactoryUtil::ROLE_EDITOR)); QString str; QTextStream buf(&str); buf << newWorkbook->GetClassName() << newWorkbook.GetPointer(); newWorkbook->SetID(str); return newWorkbook; } void* EditorSashContainer::CreateParent(void* parentWidget) { //return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateComposite(parentWidget); return new QtDnDControlWidget(static_cast(parentWidget)); } void EditorSashContainer::DisposeParent() { this->parent = 0; } bool EditorSashContainer::IsActiveWorkbook(PartStack::Pointer workbook) { return activeEditorWorkbook == workbook; } PartStack::Pointer EditorSashContainer::CreateStack() { return this->NewEditorWorkbook(); } void EditorSashContainer::SetVisiblePart( ILayoutContainer::Pointer container, PartPane::Pointer visiblePart) { PartStack::Pointer stack = container.Cast(); if (stack == 0) return; stack->GetContainer().Cast()->SetActiveWorkbook(stack, true); stack->SetSelection(visiblePart); } LayoutPart::Pointer EditorSashContainer::GetVisiblePart( ILayoutContainer::Pointer container) { PartStack::Pointer refPart = container.Cast(); return refPart->GetSelection(); } EditorSashContainer::EditorSashContainer(const QString& editorId, WorkbenchPage* page, void* parent) : PartSashContainer(editorId, page, parent) { this->CreateDefaultWorkbook(); } bool EditorSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } void EditorSashContainer::AddEditor(PartPane::Pointer pane, PartStack::Pointer stack) { //EditorStack workbook = getActiveWorkbook(); stack->Add(pane); } void EditorSashContainer::UpdateStackButtons() { // // This is applicable only when the new // // min/max behaviour is being used // Perspective persp = getPage().getActivePerspective(); // if (!Perspective.useNewMinMax(persp)) // return; // // // Find the upper Right editor stack // LayoutPart[] stacks = getChildren(); // EditorStack winner = getUpperRightEditorStack(stacks); // // // Now hide the buttons for all but the upper right stack // for (int i = 0; i < stacks.length; i++) // { // if (!(stacks[i] instanceof EditorStack) // ) // continue; // ((EditorStack) stacks[i]).showMinMax(stacks[i] == winner); // } // // // Force the stack's presentation state to match its perspective // persp.refreshEditorAreaVisibility(); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack() { return this->GetUpperRightEditorStack(this->GetChildren()); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack( const ILayoutContainer::ChildrenType& stacks) { // Find the upper Right editor stack PartStack::Pointer winner; - Rectangle winnerRect; + QRect winnerRect; for (ILayoutContainer::ChildrenType::const_iterator iter = stacks.begin(); iter != stacks.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast() == 0) continue; PartStack::Pointer stack = part.Cast(); - Rectangle bb = stack->GetBounds(); - if (iter == stacks.begin() || bb.y < winnerRect.y || (bb.y == winnerRect.y && bb.x - > winnerRect.x)) + QRect bb = stack->GetBounds(); + if (iter == stacks.begin() || bb.y() < winnerRect.y() || (bb.y() == winnerRect.y() && bb.x() + > winnerRect.x())) { winner = stack; winnerRect = bb; } } return winner; } PartStack::Pointer EditorSashContainer::GetActiveWorkbook() { if (activeEditorWorkbook == 0) { if (editorWorkbooks.size() < 1) { this->SetActiveWorkbook(this->CreateDefaultWorkbook(), false); } else { this->SetActiveWorkbook(editorWorkbooks.front(), false); } } return activeEditorWorkbook; } QString EditorSashContainer::GetActiveWorkbookID() { return this->GetActiveWorkbook()->GetID(); } QList EditorSashContainer::GetEditorWorkbooks() { return editorWorkbooks; } std::size_t EditorSashContainer::GetEditorWorkbookCount() { return editorWorkbooks.size(); } void EditorSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { //Find the sashes around the current editor and //then the sashes around the editor area. PartSashContainer::FindSashes(pane, sashes); ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } void EditorSashContainer::RemoveAllEditors() { PartStack::Pointer currentWorkbook = this->GetActiveWorkbook(); // Iterate over a copy so the original can be modified. QList workbooks(editorWorkbooks); for (QList::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; QList children = workbook->GetChildren(); for (QList::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { workbook->Remove(*childIter); } if (workbook != currentWorkbook) { this->Remove(workbook); workbook->Dispose(); } } } void EditorSashContainer::RemoveEditor(PartPane::Pointer pane) { PartStack::Pointer workbook = pane->GetContainer().Cast(); if (workbook == 0) { return; } workbook->Remove(pane); // remove the editor workbook if empty if (workbook->GetItemCount() < 1 /* && editorWorkbooks.size() > 1*/) { // // If the user closes the last editor and the editor area // // is maximized, restore it // Perspective persp = getPage().getActivePerspective(); // if (Perspective.useNewMinMax(persp)) // { // if (persp.getPresentation().getMaximizedStack() instanceof EditorStack) // persp.getPresentation().getMaximizedStack(). // setState(IStackPresentationSite.STATE_RESTORED); // } this->Remove(workbook); workbook->Dispose(); } } bool EditorSashContainer::RestoreState(IMemento::Pointer memento) { //TODO EditorSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, 0); bool result = true; // Remove the default editor workbook that is // initialy created with the editor area. // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { PartStack::Pointer defaultWorkbook; for (ILayoutContainer::ChildrenType::iterator i = children.begin(); i != children.end(); ++i) { LayoutPart::Pointer child = *i; if (child->GetID() == DEFAULT_WORKBOOK_ID) { defaultWorkbook = child.Cast(); if (defaultWorkbook->GetItemCount() > 0) { defaultWorkbook = 0; } } } if (defaultWorkbook) { Remove(defaultWorkbook); } // }} // ); // Restore the relationship/layout QList infos(memento->GetChildren(WorkbenchConstants::TAG_INFO)); QHash mapIDtoPart; for (int i = 0; i < infos.size(); i++) { // Get the info details. IMemento::Pointer childMem = infos[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); } PartStack::Pointer workbook; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Create the part. workbook = NewEditorWorkbook(); workbook->SetID(partID); // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active workbook->SetContainer(ILayoutContainer::Pointer(this)); // }} // ); IMemento::Pointer workbookMemento = childMem->GetChild( WorkbenchConstants::TAG_FOLDER); if (workbookMemento) { //result.add(workbook[0].restoreState(workbookMemento)); result &= workbook->RestoreState(workbookMemento); } const int myLeft = left, myRight = right, myRelationship = relationship; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.isEmpty()) { Add(workbook); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { Add(workbook, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = workbook; } return result; } bool EditorSashContainer::SaveState(IMemento::Pointer memento) { QList relationships(ComputeRelation()); // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, 0); bool result = true; for (int i = 0; i < relationships.size(); i++) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; const RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); PartStack::Pointer stack = info.part.Cast(); if (stack) { IMemento::Pointer folderMem = childMem->CreateChild( WorkbenchConstants::TAG_FOLDER); //result.add(stack.saveState(folderMem)); result &= stack->SaveState(folderMem); } if (info.relative != 0) { 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); } } return result; } void EditorSashContainer::SetActiveWorkbook(PartStack::Pointer newWorkbook, bool hasFocus) { if (newWorkbook != 0) { if (std::find(editorWorkbooks.begin(), editorWorkbooks.end(), newWorkbook) == editorWorkbooks.end()) { return; } } PartStack::Pointer oldWorkbook = activeEditorWorkbook; activeEditorWorkbook = newWorkbook; if (oldWorkbook != 0 && oldWorkbook != newWorkbook) { oldWorkbook->SetActive(StackPresentation::AS_INACTIVE); } if (newWorkbook != 0) { if (hasFocus) { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } else { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_NOFOCUS); } } this->UpdateTabList(); } void EditorSashContainer::SetActiveWorkbookFromID(const QString& id) { for (QList::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { this->SetActiveWorkbook(workbook, false); } } } PartStack::Pointer EditorSashContainer::GetWorkbookFromID(const QString& id) { for (QList::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { return workbook; } } return PartStack::Pointer(0); } void EditorSashContainer::UpdateTabList() { void* parent = this->GetParent(); if (parent != 0) { // parent may be 0 on startup PartStack::Pointer wb(this->GetActiveWorkbook()); //TODO EditorSashContainer update tab list // if (wb == 0) // { // parent.setTabList(new Control[0]); // } // else // { // parent.setTabList(wb.getTabList()); // } } } void EditorSashContainer::CreateControl(void* parent) { PartSashContainer::CreateControl(parent); ///let the user drop files/editor input on the editor area this->AddDropSupport(); } bool EditorSashContainer::IsCompressible() { //Added for bug 19524 return true; } bool EditorSashContainer::IsStackType(ILayoutContainer::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR); } bool EditorSashContainer::IsPaneType(LayoutPart::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool EditorSashContainer::RestorePresentationState(IMemento::Pointer /*areaMem*/) { QList workbooks = this->GetEditorWorkbooks(); for (QList::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; IMemento::Pointer memento = workbook->GetSavedPresentationState(); if (memento == 0) { continue; } QList parts = workbook->GetPresentableParts(); PresentationSerializer serializer(parts); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void runWithException() throws Throwable // { workbook->GetPresentation()->RestoreState(&serializer, memento); // }} // ); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h index 8ecc015846..9e5ddeea3e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h @@ -1,67 +1,65 @@ /*=================================================================== 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 BERRYIDRAGOVERLISTENER_H_ #define BERRYIDRAGOVERLISTENER_H_ #include -#include "berryPoint.h" -#include "berryRectangle.h" - +#include "berryObject.h" #include "berryIDropTarget.h" namespace berry { /** * Implementers of this interface will receive notifications when objects are dragged over * a particular control. */ struct IDragOverListener { struct Events { - typedef Message4 DragEventType; - typedef MessageDelegate4 DragDelegate; + typedef Message4 DragEventType; + typedef MessageDelegate4 DragDelegate; DragEventType drag; void AddListener(IDragOverListener* listener); void RemoveListener(IDragOverListener* listener); }; virtual ~IDragOverListener(); /** * Notifies the receiver that the given object has been dragged over * the given position. Returns a drop target if the object may be * dropped in this position. Returns null otherwise. * * @param draggedObject object being dragged over this location * @param position location of the cursor * @param dragRectangle current drag rectangle (may be an empty rectangle if none) * @return a valid drop target or null if none */ virtual IDropTarget::Pointer Drag(void* currentControl, const Object::Pointer& draggedObject, - const Point& position, const Rectangle& dragRectangle) = 0; + const QPoint& position, const QRect& dragRectangle) = 0; }; } #endif /* BERRYIDRAGOVERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDropTarget.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDropTarget.h index 0304b77b5d..f2e3d0ddb8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDropTarget.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDropTarget.h @@ -1,71 +1,73 @@ /*=================================================================== 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 BERRYIDROPTARGET_H_ #define BERRYIDROPTARGET_H_ #include +#include +#include -#include "berryRectangle.h" -#include "tweaklets/berryDnDTweaklet.h" +#include namespace berry { /** * This interface is used to drop objects. It knows how to drop a particular object * in a particular location. IDropTargets are typically created by IDragOverListeners, and * it is the job of the IDragOverListener to supply the drop target with information about * the object currently being dragged. * * @see IDragOverListener */ -struct BERRY_UI_QT IDropTarget : public Object { +struct BERRY_UI_QT IDropTarget : public Object +{ - berryObjectMacro(IDropTarget); + berryObjectMacro(IDropTarget) ~IDropTarget(); /** * Drops the object in this position */ virtual void Drop() = 0; /** * Returns a cursor id describing this drop operation * * @return a cursor id describing this drop operation */ - virtual DnDTweaklet::CursorType GetCursor() = 0; + virtual CursorType GetCursor() = 0; /** * Returns a rectangle (screen coordinates) describing the target location * for this drop operation. * * @return a snap rectangle or null if this drop target does not have a specific snap * location. */ - virtual Rectangle GetSnapRectangle() = 0; + virtual QRect GetSnapRectangle() = 0; /** * This is called whenever a drag operation is cancelled */ virtual void DragFinished(bool dropPerformed) = 0; }; } #endif /* BERRYIDROPTARGET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp index 00fc90488c..cfbb0c9b37 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp @@ -1,347 +1,345 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryDetachedWindow.h" #include "berryIWorkbenchWindow.h" #include "berryConstants.h" namespace berry { const QString LayoutPart::PROP_VISIBILITY = "PROP_VISIBILITY"; LayoutPart::LayoutPart(const QString& id_) : container(0), id(id_), deferCount(0) { } LayoutPart::~LayoutPart() { } bool LayoutPart::AllowsAutoFocus() { if (container != 0) { return container->AllowsAutoFocus(); } return true; } void LayoutPart::Dispose() { } -Rectangle LayoutPart::GetBounds() +QRect LayoutPart::GetBounds() { if (this->GetControl() == 0) - return Rectangle(); + return QRect(); return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetControl()); } ILayoutContainer::Pointer LayoutPart::GetContainer() { return ILayoutContainer::Pointer(container); } bool LayoutPart::IsPlaceHolder() const { return false; } QString LayoutPart::GetID() const { return id; } bool LayoutPart::IsCompressible() { return false; } -Point LayoutPart::GetSize() +QSize LayoutPart::GetSize() { - Rectangle r = this->GetBounds(); - Point ptSize(r.width, r.height); - return ptSize; + return this->GetBounds().size(); } int LayoutPart::GetSizeFlags(bool /*horizontal*/) { return Constants::MIN; } int LayoutPart::ComputePreferredSize(bool /*width*/, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredParallel) { return preferredParallel; } -IDropTarget::Pointer LayoutPart::GetDropTarget(Object::Pointer /*draggedObject*/, const Point& /*displayCoordinates*/) +IDropTarget::Pointer LayoutPart::GetDropTarget(Object::Pointer /*draggedObject*/, const QPoint& /*displayCoordinates*/) { return IDropTarget::Pointer(0); } bool LayoutPart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer LayoutPart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer LayoutPart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } void LayoutPart::MoveAbove(void* /*refControl*/) { } void LayoutPart::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } bool LayoutPart::GetVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl); } return false; } bool LayoutPart::IsVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsVisible(ctrl); } return false; } void LayoutPart::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); if (ctrl != 0) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } // if (!makeVisible && this->IsFocusAncestor(ctrl)) // { // // Workaround for Bug 60970 [EditorMgmt] setActive() called on an editor when it does not have focus. // // Force focus on the shell so that when ctrl is hidden, // // SWT does not try to send focus elsewhere, which may cause // // some other part to be activated, which affects the part // // activation order and can cause flicker. // ctrl.getShell().forceFocus(); // } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(ctrl, makeVisible); } } bool LayoutPart::IsFocusAncestor(void* /*ctrl*/) { // Control f = ctrl.getDisplay().getFocusControl(); // while (f != null && f != ctrl) // { // f = f.getParent(); // } // return f == ctrl; return false; } -void LayoutPart::SetBounds(const Rectangle& r) +void LayoutPart::SetBounds(const QRect& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } void LayoutPart::SetContainer(ILayoutContainer::Pointer container) { this->container = container.GetPointer(); //TODO Zoom // if (container != 0) // { // setZoomed(container.childIsZoomed(this)); // } } void LayoutPart::SetFocus() { } void LayoutPart::SetID(const QString& str) { id = str; } LayoutPart::Pointer LayoutPart::GetPart() { return LayoutPart::Pointer(this); } void LayoutPart::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferringEvents(); } deferCount++; } else { if (deferCount> 0) { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } } void LayoutPart::StartDeferringEvents() { } void LayoutPart::HandleDeferredEvents() { } bool LayoutPart::IsDeferred() { return deferCount> 0; } void LayoutPart::DescribeLayout(QString& /*buf*/) const { } QString LayoutPart::GetPlaceHolderId() { return this->GetID(); } void LayoutPart::ResizeChild(LayoutPart::Pointer /*childThatChanged*/) { } void LayoutPart::FlushLayout() { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->ResizeChild(LayoutPart::Pointer(this)); } } bool LayoutPart::AllowsAdd(LayoutPart::Pointer /*toAdd*/) { return false; } QString LayoutPart::ToString() const { return ""; } void LayoutPart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h index 182d188152..86d5c4eb0f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h @@ -1,305 +1,303 @@ /*=================================================================== 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 BERRYLAYOUTPART_H_ #define BERRYLAYOUTPART_H_ #include #include "berryIDropTarget.h" #include "berryISizeProvider.h" -#include "berryRectangle.h" -#include "berryPoint.h" #include "berryShell.h" namespace berry { struct ILayoutContainer; struct IWorkbenchWindow; /** * \ingroup org_blueberry_ui_internal * * A presentation part is used to build the presentation for the * workbench. Common subclasses are pane and folder. */ class LayoutPart : virtual public Object, public virtual ISizeProvider { public: berryObjectMacro(LayoutPart) protected: ILayoutContainer* container; protected: QString id; public: static const QString PROP_VISIBILITY;// = "PROP_VISIBILITY"; /** * Number of times deferUpdates(true) has been called without a corresponding * deferUpdates(false) */ private: int deferCount; /** * PresentationPart constructor comment. */ public: LayoutPart(const QString& id); public: virtual ~LayoutPart(); /** * When a layout part closes, focus will return to a previously active part. * This method determines whether this part should be considered for activation * when another part closes. If a group of parts are all closing at the same time, * they will all return false from this method while closing to ensure that the * parent does not activate a part that is in the process of closing. Parts will * also return false from this method if they are minimized, closed fast views, * obscured by zoom, etc. * * @return true iff the parts in this container may be given focus when the active * part is closed */ public: virtual bool AllowsAutoFocus(); /** * Creates the GUI control */ public: virtual void CreateControl(void* parent) = 0; /** * Disposes the GUI control * * This can be used to execute cleanup code or notify listeners * when a LayoutPart is no longer used, but is still referenced * by a SmartPointer (instead of putting the code in the LayoutPart * destructor). */ public: virtual void Dispose(); /** * Gets the presentation bounds. */ - public: Rectangle GetBounds(); + public: QRect GetBounds(); /** * Gets the parent for this part. *

* In general, this is non-null if the object has been added to a container and the * container's widgetry exists. The exception to this rule is PartPlaceholders * created when restoring a ViewStack using restoreState, which point to the * ViewStack even if its widgetry doesn't exist yet. Returns null in the remaining * cases. *

*

* TODO: change the semantics of this method to always point to the parent container, * regardless of whether its widgetry exists. Locate and refactor code that is currently * depending on the special cases. *

*/ public: virtual SmartPointer GetContainer(); /** * Get the part control. This method may return null. */ public: virtual void* GetControl() = 0; public: virtual bool IsPlaceHolder() const; /** * Gets the ID for this part. */ public: virtual QString GetID() const; public: virtual bool IsCompressible(); /** * Gets the presentation size. */ - public: virtual Point GetSize(); + public: virtual QSize GetSize(); /** * @see org.blueberry.ui.presentations.StackPresentation#getSizeFlags(boolean) * * @since 3.1 */ public: virtual int GetSizeFlags(bool horizontal); /** * @see org.blueberry.ui.presentations.StackPresentation#computePreferredSize(boolean, int, int, int) * * @since 3.1 */ public: virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); - public: virtual IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const Point& displayCoordinates); + public: virtual IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const QPoint& displayCoordinates); public: bool IsDocked(); public: virtual Shell::Pointer GetShell(); /** * Returns the workbench window window for a part. * * @return the workbench window, or null if there's no window * associated with this part. */ public: virtual SmartPointer GetWorkbenchWindow(); /** * Move the control over another one. */ public: virtual void MoveAbove(void* refControl); /** * Reparent a part. */ public: virtual void Reparent(void* newParent); /** * Returns true if this part was set visible. This returns whatever was last passed into * setVisible, but does not necessarily indicate that the part can be seen (ie: one of its * ancestors may be invisible) */ public: virtual bool GetVisible(); /** * Returns true if this part can be seen. Returns false if the part or any of its ancestors * are invisible. */ public: virtual bool IsVisible(); /** * Shows the receiver if visible is true otherwise hide it. */ public: virtual void SetVisible(bool makeVisible); /** * Returns true if the given control or any of its descendents has focus. */ private: virtual bool IsFocusAncestor(void* ctrl); /** * Sets the presentation bounds. */ - public: virtual void SetBounds(const Rectangle& r); + public: virtual void SetBounds(const QRect& r); /** * Sets the parent for this part. */ public: virtual void SetContainer(SmartPointer container); /** * Sets focus to this part. */ public: virtual void SetFocus(); /** * Sets the part ID. */ public: virtual void SetID(const QString& str); /* (non-Javadoc) * @see org.blueberry.ui.internal.IWorkbenchDragDropPart#getPart() */ public: virtual LayoutPart::Pointer GetPart(); /** * deferUpdates(true) disables widget updates until a corresponding call to * deferUpdates(false). Exactly what gets deferred is the decision * of each LayoutPart, however the part may only defer operations in a manner * that does not affect the final result. * That is, the state of the receiver after the final call to deferUpdates(false) * must be exactly the same as it would have been if nothing had been deferred. * * @param shouldDefer true iff events should be deferred */ public: void DeferUpdates(bool shouldDefer); /** * This is called when deferUpdates(true) causes UI events for this * part to be deferred. Subclasses can overload to initialize any data * structures that they will use to collect deferred events. */ protected: virtual void StartDeferringEvents(); /** * Immediately processes all UI events which were deferred due to a call to * deferUpdates(true). This is called when the last call is made to * deferUpdates(false). Subclasses should overload this method if they * defer some or all UI processing during deferUpdates. */ protected: virtual void HandleDeferredEvents(); /** * Subclasses can call this method to determine whether UI updates should * be deferred. Returns true iff there have been any calls to deferUpdates(true) * without a corresponding call to deferUpdates(false). Any operation which is * deferred based on the result of this method should be performed later within * handleDeferredEvents(). * * @return true iff updates should be deferred. */ protected: bool IsDeferred(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: virtual void DescribeLayout(QString& buf) const; /** * Returns an id representing this part, suitable for use in a placeholder. * * @since 3.0 */ public: virtual QString GetPlaceHolderId(); public: virtual void ResizeChild(LayoutPart::Pointer childThatChanged); public: void FlushLayout(); /** * Returns true iff the given part can be added to this ILayoutContainer * @param toAdd * @return * @since 3.1 */ public: virtual bool AllowsAdd(LayoutPart::Pointer toAdd); /** * Tests the integrity of this object. Throws an exception if the object's state * is not internally consistent. For use in test suites. */ public: virtual void TestInvariants(); public: virtual QString ToString() const; }; } #endif /*BERRYLAYOUTPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp index 2d8dff9339..82c3ecf95e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp @@ -1,306 +1,306 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryLayoutPartSash.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryWorkbenchPlugin.h" #include "berryConstants.h" namespace berry { LayoutPartSash::SelectionListener::SelectionListener(LayoutPartSash* lp) : layoutPartSash(lp) { } void LayoutPartSash::SelectionListener::WidgetSelected(GuiTk::SelectionEvent::Pointer e) { layoutPartSash->CheckDragLimit(e); if (e->detail != Constants::DRAG) { layoutPartSash->WidgetSelected(e->x, e->y, e->width, e->height); } } LayoutPartSash::LayoutPartSash(PartSashContainer* rootContainer, int style) : LayoutPart(""), sash(0), enabled(false), rootContainer(rootContainer), style(style), left(300), right(300), presFactory(0), isVisible(false) { selectionListener = new SelectionListener(this); } LayoutPartSash::~LayoutPartSash() { this->Dispose(); } void LayoutPartSash::CheckDragLimit(GuiTk::SelectionEvent::Pointer event) { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); - Rectangle nodeBounds = node->GetBounds(); - Rectangle eventRect(event->x, event->y, event->width, event->height); + QRect nodeBounds = node->GetBounds(); + QRect eventRect(event->x, event->y, event->width, event->height); bool vertical = (style == Constants::VERTICAL); // If a horizontal sash, flip the coordinate system so that we // can handle horizontal and vertical sashes without special cases if (!vertical) { - nodeBounds.FlipXY(); - eventRect.FlipXY(); + nodeBounds = QRect(nodeBounds.y(), nodeBounds.x(), nodeBounds.height(), nodeBounds.width()); + eventRect = QRect(eventRect.y(), eventRect.x(), eventRect.height(), eventRect.width()); } - int eventX = eventRect.x; - int left = std::max(0, eventX - nodeBounds.x); - left = std::min(left, nodeBounds.width - this->GetSashSize()); - int right = nodeBounds.width - left - this->GetSashSize(); + int eventX = eventRect.x(); + int left = std::max(0, eventX - nodeBounds.x()); + left = std::min(left, nodeBounds.width() - this->GetSashSize()); + int right = nodeBounds.width() - left - this->GetSashSize(); - LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width, nodeBounds.height, left, right, nodeBounds.width); + LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width(), nodeBounds.height(), left, right, nodeBounds.width()); - eventRect.x = nodeBounds.x + sizes.left; + eventRect.setX(nodeBounds.x() + sizes.left); // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { - eventRect.FlipXY(); + eventRect = QRect(eventRect.y(), eventRect.x(), eventRect.height(), eventRect.width()); } - event->x = eventRect.x; - event->y = eventRect.y; + event->x = eventRect.x(); + event->y = eventRect.y(); } void LayoutPartSash::CreateControl(void* /*parent*/) { // Defer creation of the control until it becomes visible if (isVisible) { this->DoCreateControl(); } } void LayoutPartSash::DoCreateControl() { if (sash == 0) { // ask the presentation factory to create the sash IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; sash = factory->CreateSash(this->rootContainer->GetParent(), sashStyle); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddSelectionListener(sash, selectionListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(sash, bounds); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(sash, isVisible); } } -void LayoutPartSash::SetBounds(const Rectangle& r) +void LayoutPartSash::SetBounds(const QRect& r) { LayoutPart::SetBounds(r); bounds = r; } void LayoutPartSash::SetVisible(bool visible) { if (visible == isVisible) { return; } if (visible) { this->DoCreateControl(); } else { this->Dispose(); } LayoutPart::SetVisible(visible); isVisible = visible; } bool LayoutPartSash::IsVisible() { return isVisible; } void LayoutPartSash::Dispose() { if (sash != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(sash); } sash = 0; } -Rectangle LayoutPartSash::GetBounds() +QRect LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } void* LayoutPartSash::GetControl() { return sash; } QString LayoutPartSash::GetID() const { return ""; } LayoutPartSash::Pointer LayoutPartSash::GetPostLimit() { return postLimit; } LayoutPartSash::Pointer LayoutPartSash::GetPreLimit() { return preLimit; } int LayoutPartSash::GetLeft() { return left; } int LayoutPartSash::GetRight() { return right; } bool LayoutPartSash::IsHorizontal() { return ((style & Constants::HORIZONTAL) == Constants::HORIZONTAL); } bool LayoutPartSash::IsVertical() { return ((style & Constants::VERTICAL) == Constants::VERTICAL); } void LayoutPartSash::SetPostLimit(LayoutPartSash::Pointer newPostLimit) { postLimit = newPostLimit; } void LayoutPartSash::SetPreLimit(LayoutPartSash::Pointer newPreLimit) { preLimit = newPreLimit; } void LayoutPartSash::SetRatio(float newRatio) { int total = left + right; int newLeft = (int) (total * newRatio); this->SetSizes(newLeft, total - newLeft); } void LayoutPartSash::SetSizes(int left, int right) { if (left < 0 || right < 0) { return; } if (left == this->left && right == this->right) { return; } this->left = left; this->right = right; this->FlushCache(); } void LayoutPartSash::FlushCache() { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); if (root != 0) { LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); if (node != 0) { node->FlushCache(); } } } void LayoutPartSash::WidgetSelected(int x, int y, int /*width*/, int /*height*/) { if (!enabled) { return; } LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); - Rectangle nodeBounds = node->GetBounds(); + QRect nodeBounds = node->GetBounds(); //Recompute ratio - x -= nodeBounds.x; - y -= nodeBounds.y; + x -= nodeBounds.x(); + y -= nodeBounds.y(); if (style == Constants::VERTICAL) { - this->SetSizes(x, nodeBounds.width - x - this->GetSashSize()); + this->SetSizes(x, nodeBounds.width() - x - this->GetSashSize()); } else { - this->SetSizes(y, nodeBounds.height - y - this->GetSashSize()); + this->SetSizes(y, nodeBounds.height() - y - this->GetSashSize()); } node->SetBounds(nodeBounds); } void LayoutPartSash::SetEnabled(bool resizable) { this->enabled = resizable; if (sash != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); } } int LayoutPartSash::GetSashSize() const { IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; int size = factory->GetSashSize(sashStyle); return size; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h index 268407b6a1..ef5d5dadfc 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h @@ -1,182 +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. ===================================================================*/ #ifndef BERRYLAYOUTPARTSASH_H_ #define BERRYLAYOUTPARTSASH_H_ #include "berryLayoutPart.h" #include "berryPartSashContainer.h" #include "guitk/berryGuiTkISelectionListener.h" #include "presentations/berryIPresentationFactory.h" +#include + namespace berry { class LayoutPartSash: public LayoutPart { friend class WorkbenchPage; friend class PartSashContainer; friend class LayoutTreeNode; public: berryObjectMacro(LayoutPartSash); LayoutPartSash(PartSashContainer* rootContainer, int style); ~LayoutPartSash(); private: void* sash; bool enabled; PartSashContainer* rootContainer; int style; LayoutPartSash::Pointer preLimit; LayoutPartSash::Pointer postLimit; int left; int right; - Rectangle bounds; + QRect bounds; IPresentationFactory* presFactory; /** * Stores whether or not the sash is visible. (This is expected to have a meaningful * value even if the underlying control doesn't exist). */ bool isVisible; struct SelectionListener : public GuiTk::ISelectionListener { SelectionListener(LayoutPartSash* layoutPartSash); void WidgetSelected(GuiTk::SelectionEvent::Pointer e); private: LayoutPartSash* layoutPartSash; }; GuiTk::ISelectionListener::Pointer selectionListener; // checkDragLimit contains changes by cagatayk@acm.org void CheckDragLimit(GuiTk::SelectionEvent::Pointer event); /** * Creates the control. As an optimization, creation of the control is deferred if * the control is invisible. */ public: void CreateControl(void* parent); /** * Creates the underlying SWT control. * * @since 3.1 */ private: void DoCreateControl(); public: - void SetBounds(const Rectangle& r); + void SetBounds(const QRect& r); /** * Makes the sash visible or invisible. Note: as an optimization, the actual widget is destroyed when the * sash is invisible. */ public: void SetVisible(bool visible); public: bool IsVisible(); /** * See LayoutPart#dispose */ public: void Dispose(); /** * Gets the presentation bounds. */ public: - Rectangle GetBounds(); + QRect GetBounds(); /** * Returns the part control. */ public: void* GetControl(); /** * */ public: QString GetID() const; protected: LayoutPartSash::Pointer GetPostLimit(); LayoutPartSash::Pointer GetPreLimit(); int GetLeft(); int GetRight(); bool IsHorizontal(); bool IsVertical(); void SetPostLimit(LayoutPartSash::Pointer newPostLimit); void SetPreLimit(LayoutPartSash::Pointer newPreLimit); void SetRatio(float newRatio); void SetSizes(int left, int right); private: void FlushCache(); private: void WidgetSelected(int x, int y, int width, int height); /** * @param resizable * @since 3.1 */ public: void SetEnabled(bool resizable); protected: /* package */int GetSashSize() const; }; } #endif /* BERRYLAYOUTPARTSASH_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp index bc08e19e2d..fdab418d8c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp @@ -1,480 +1,481 @@ /*=================================================================== 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 "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryLayoutPartSash.h" #include "berryConstants.h" +#include "berryLog.h" namespace berry { int LayoutTree::minCacheHits = 0; int LayoutTree::minCacheMisses = 0; int LayoutTree::maxCacheHits = 0; int LayoutTree::maxCacheMisses = 0; LayoutTree::LayoutTree(LayoutPart::Pointer part) : parent(0), cachedMinimumWidthHint(Constants::DEFAULT), cachedMinimumWidth(Constants::DEFAULT), cachedMinimumHeightHint(Constants::DEFAULT), cachedMinimumHeight(Constants::DEFAULT), cachedMaximumWidthHint(Constants::DEFAULT), cachedMaximumWidth(Constants::DEFAULT), cachedMaximumHeightHint(Constants::DEFAULT), cachedMaximumHeight(Constants::DEFAULT), forceLayout(true), sizeFlagsDirty(true), widthSizeFlags(0), heightSizeFlags(0) { this->part = part; } LayoutPart::Pointer LayoutTree::ComputeRelation( QList& /*relations*/) { return part; } -LayoutPart::Pointer LayoutTree::FindPart(const Point& /*toFind*/) +LayoutPart::Pointer LayoutTree::FindPart(const QPoint& /*toFind*/) { return part; } void LayoutTree::DisposeSashes() { } LayoutTree::Pointer LayoutTree::Find(LayoutPart::Pointer child) { if (part != child) { return LayoutTree::Pointer(0); } return LayoutTree::Pointer(this); } void LayoutTree::FindSashes(PartPane::Sashes sashes) { if (this->GetParent() == 0) { return; } this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes); } LayoutPart::Pointer LayoutTree::FindBottomRight() { return part; } LayoutTreeNode::Pointer LayoutTree::FindSash(LayoutPartSash::Pointer /*sash*/) { return LayoutTreeNode::Pointer(0); } -Rectangle LayoutTree::GetBounds() +QRect LayoutTree::GetBounds() { return currentBounds; } int LayoutTree::Subtract(int a, int b) { poco_assert(b >= 0 && b < INF); return Add(a, -b); } int LayoutTree::Add(int a, int b) { if (a == INF || b == INF) { return INF; } return a + b; } void LayoutTree::AssertValidSize(int toCheck) { poco_assert(toCheck >= 0 && (toCheck == INF || toCheck < INF / 2)); } int LayoutTree::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { this->AssertValidSize(availableParallel); this->AssertValidSize(availablePerpendicular); this->AssertValidSize(preferredParallel); if (!this->IsVisible()) { return 0; } if (availableParallel == 0) { return 0; } if (preferredParallel == 0) { return std::min(availableParallel, this->ComputeMinimumSize(width, availablePerpendicular)); } else if (preferredParallel == INF && availableParallel == INF) { return this->ComputeMaximumSize(width, availablePerpendicular); } // Optimization: if this subtree doesn't have any size preferences beyond its minimum and maximum // size, simply return the preferred size if (!this->HasSizeFlag(width, Constants::FILL)) { return preferredParallel; } int result = this->DoComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); return result; } int LayoutTree::DoGetSizeFlags(bool width) { return part->GetSizeFlags(width); } int LayoutTree::DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { int result = std::min(availableParallel, part->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel)); this->AssertValidSize(result); return result; } int LayoutTree::ComputeMinimumSize(bool width, int availablePerpendicular) { this->AssertValidSize(availablePerpendicular); // Optimization: if this subtree has no minimum size, then always return 0 as its // minimum size. if (!this->HasSizeFlag(width, Constants::MIN)) { return 0; } // If this subtree doesn't contain any wrapping controls (ie: they don't care // about their perpendicular size) then force the perpendicular // size to be INF. This ensures that we will get a cache hit // every time for non-wrapping controls. if (!this->HasSizeFlag(width, Constants::WRAP)) { availablePerpendicular = INF; } if (width) { // Check if we have a cached width measurement (we can only return a cached // value if we computed it for the same height) if (cachedMinimumWidthHint == availablePerpendicular) { minCacheHits++; return cachedMinimumWidth; } // Recompute the minimum width and store it in the cache minCacheMisses++; int result = this->DoComputeMinimumSize(width, availablePerpendicular); cachedMinimumWidth = result; cachedMinimumWidthHint = availablePerpendicular; return result; } else { // Check if we have a cached height measurement (we can only return a cached // value if we computed it for the same width) if (cachedMinimumHeightHint == availablePerpendicular) { minCacheHits++; return cachedMinimumHeight; } // Recompute the minimum width and store it in the cache minCacheMisses++; int result = this->DoComputeMinimumSize(width, availablePerpendicular); cachedMinimumHeight = result; cachedMinimumHeightHint = availablePerpendicular; return result; } } void LayoutTree::PrintCacheStatistics() { BERRY_INFO << "minimize cache " << minCacheHits << " / " << (minCacheHits + minCacheMisses) << " hits " << (minCacheHits * 100 / (minCacheHits + minCacheMisses)) << "%\n"; BERRY_INFO << "maximize cache " << maxCacheHits << " / " << (maxCacheHits + maxCacheMisses) << " hits" << (maxCacheHits * 100 / (maxCacheHits + maxCacheMisses)) << "%\n"; } int LayoutTree::DoComputeMinimumSize(bool width, int availablePerpendicular) { int result = this->DoComputePreferredSize(width, INF, availablePerpendicular, 0); this->AssertValidSize(result); return result; } int LayoutTree::ComputeMaximumSize(bool width, int availablePerpendicular) { this->AssertValidSize(availablePerpendicular); // Optimization: if this subtree has no maximum size, then always return INF as its // maximum size. if (!this->HasSizeFlag(width, Constants::MAX)) { return INF; } // If this subtree doesn't contain any wrapping controls (ie: they don't care // about their perpendicular size) then force the perpendicular // size to be INF. This ensures that we will get a cache hit // every time. if (!this->HasSizeFlag(width, Constants::WRAP)) { availablePerpendicular = INF; } if (width) { // Check if we have a cached width measurement (we can only return a cached // value if we computed it for the same height) if (cachedMaximumWidthHint == availablePerpendicular) { maxCacheHits++; return cachedMaximumWidth; } maxCacheMisses++; // Recompute the maximum width and store it in the cache int result = this->DoComputeMaximumSize(width, availablePerpendicular); cachedMaximumWidth = result; cachedMaximumWidthHint = availablePerpendicular; return result; } else { // Check if we have a cached height measurement if (cachedMaximumHeightHint == availablePerpendicular) { maxCacheHits++; return cachedMaximumHeight; } maxCacheMisses++; // Recompute the maximum height and store it in the cache int result = this->DoComputeMaximumSize(width, availablePerpendicular); cachedMaximumHeight = result; cachedMaximumHeightHint = availablePerpendicular; return result; } } int LayoutTree::DoComputeMaximumSize(bool width, int availablePerpendicular) { return this->DoComputePreferredSize(width, INF, availablePerpendicular, INF); } void LayoutTree::FlushNode() { // Clear cached sizes cachedMinimumWidthHint = Constants::DEFAULT; cachedMinimumWidth = Constants::DEFAULT; cachedMinimumHeightHint = Constants::DEFAULT; cachedMinimumHeight = Constants::DEFAULT; cachedMaximumWidthHint = Constants::DEFAULT; cachedMaximumWidth = Constants::DEFAULT; cachedMaximumHeightHint = Constants::DEFAULT; cachedMaximumHeight = Constants::DEFAULT; // Flags may have changed. Ensure that they are recomputed the next time around sizeFlagsDirty = true; // The next setBounds call should trigger a layout even if set to the same bounds since // one of the children has changed. forceLayout = true; } void LayoutTree::FlushChildren() { this->FlushNode(); } void LayoutTree::FlushCache() { this->FlushNode(); if (parent != 0) { parent->FlushCache(); } } int LayoutTree::GetSizeFlags(bool width) { if (sizeFlagsDirty) { widthSizeFlags = this->DoGetSizeFlags(true); heightSizeFlags = this->DoGetSizeFlags(false); sizeFlagsDirty = false; } return width ? widthSizeFlags : heightSizeFlags; } LayoutTreeNode* LayoutTree::GetParent() const { return parent; } LayoutTree::Pointer LayoutTree::Insert(LayoutPart::Pointer child, bool left, LayoutPartSash::Pointer sash, LayoutPart::Pointer relative) { LayoutTree::Pointer relativeChild = this->Find(relative); LayoutTreeNode::Pointer node(new LayoutTreeNode(sash)); if (relativeChild == 0) { //Did not find the relative part. Insert beside the root. node->SetChild(left, child); node->SetChild(!left, LayoutTree::Pointer(this)); return node; } else { LayoutTreeNode* oldParent = relativeChild->GetParent(); node->SetChild(left, child); node->SetChild(!left, relativeChild); if (oldParent == 0) { //It was the root. Return a new root. return node; } oldParent->ReplaceChild(relativeChild, node); return LayoutTree::Pointer(this); } } bool LayoutTree::IsCompressible() { //Added for bug 19524 return part->IsCompressible(); } bool LayoutTree::IsVisible() { return !part->IsPlaceHolder(); } void LayoutTree::RecomputeRatio() { } LayoutTree::Pointer LayoutTree::Remove(LayoutPart::Pointer child) { LayoutTree::Pointer tree = this->Find(child); if (tree == 0) { return LayoutTree::Pointer(this); } LayoutTreeNode::Pointer oldParent(tree->GetParent()); if (oldParent == 0) { //It was the root and the only child of this tree return LayoutTree::Pointer(0); } if (oldParent->GetParent() == 0) { return oldParent->Remove(tree); } oldParent->Remove(tree); return LayoutTree::Pointer(this); } -void LayoutTree::SetBounds(const Rectangle& bounds) +void LayoutTree::SetBounds(const QRect& bounds) { if (!(bounds == currentBounds) || forceLayout) { currentBounds = bounds; this->DoSetBounds(currentBounds); forceLayout = false; } } -void LayoutTree::DoSetBounds(const Rectangle& bounds) +void LayoutTree::DoSetBounds(const QRect& bounds) { part->SetBounds(bounds); } void LayoutTree::SetParent(LayoutTreeNode* parent) { this->parent = parent; } void LayoutTree::SetPart(LayoutPart::Pointer part) { this->part = part; this->FlushCache(); } QString LayoutTree::ToString() const { return "(" + part->ToString() + ")"; } void LayoutTree::CreateControl(void* /*parent*/) { } void LayoutTree::DescribeLayout(QString& buf) const { part->DescribeLayout(buf); } bool LayoutTree::HasSizeFlag(bool width, int flag) { return (this->GetSizeFlags(width) & flag) != 0; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h index 68f81a282e..9cb62bd853 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h @@ -1,371 +1,370 @@ /*=================================================================== 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 BERRYLAYOUTTREE_H_ #define BERRYLAYOUTTREE_H_ #include "berryISizeProvider.h" -#include "berryRectangle.h" -#include "berryPoint.h" - #include "berryPartSashContainer.h" +#include + namespace berry { class LayoutTreeNode; class LayoutPartSash; /** * \ingroup org_blueberry_ui_internal * * Implementation of a tree where the node is allways a sash * and it allways has two chidren. If a children is removed * the sash, ie the node, is removed as well and its other children * placed on its parent. */ class LayoutTree : public Object, public ISizeProvider { //implements ISizeProvider { public: berryObjectMacro(LayoutTree) /* The parent of this tree or null if it is the root */ LayoutTreeNode* parent; /* Any LayoutPart if this is a leaf or a LayoutSashPart if it is a node */ LayoutPart::Pointer part; private: // Cached information int cachedMinimumWidthHint; int cachedMinimumWidth; int cachedMinimumHeightHint; int cachedMinimumHeight; int cachedMaximumWidthHint; int cachedMaximumWidth; int cachedMaximumHeightHint; int cachedMaximumHeight; bool forceLayout; - Rectangle currentBounds; + QRect currentBounds; // Cached size flags bool sizeFlagsDirty; int widthSizeFlags; int heightSizeFlags; public: // Cache statistics. For use in benchmarks and test suites only! static int minCacheHits; static int minCacheMisses; static int maxCacheHits; static int maxCacheMisses; /** * Initialize this tree with its part. */ LayoutTree(LayoutPart::Pointer part); /** * Add the relation ship between the children in the list * and returns the left children. */ virtual LayoutPart::Pointer ComputeRelation( QList& relations); /** * Locates the part that intersects the given point * * @param toFind * @return */ - virtual LayoutPart::Pointer FindPart(const Point& toFind); + virtual LayoutPart::Pointer FindPart(const QPoint& toFind); /** * Dispose all Sashs in this tree */ virtual void DisposeSashes(); /** * Find a LayoutPart in the tree and return its sub-tree. Returns * null if the child is not found. */ virtual SmartPointer Find(LayoutPart::Pointer child); /** * Find the Left,Right,Top and Bottom * sashes around this tree and set them * in sashes */ virtual void FindSashes(PartPane::Sashes sashes); /** * Find the part that is in the bottom right position. */ virtual LayoutPart::Pointer FindBottomRight(); /** * Find a sash in the tree and return its sub-tree. Returns * null if the sash is not found. */ virtual SmartPointer FindSash(SmartPointer sash); /** * Return the bounds of this tree which is the rectangle that * contains all Controls in this tree. */ - Rectangle GetBounds(); + QRect GetBounds(); /** * Subtracts two integers. If a is INF, this is treated as * positive infinity. * * @param a a positive integer or INF indicating positive infinity * @param b a positive integer (may not be INF) * @return a - b, or INF if a == INF * @since 3.1 */ static int Subtract(int a, int b); /** * Adds two positive integers. Treates INF as positive infinity. * * @param a a positive integer * @param b a positive integer * @return a + b, or INF if a or b are positive infinity * @since 3.1 */ static int Add(int a, int b); /** * Asserts that toCheck is a positive integer less than INF / 2 or equal * to INF. Many of the methods of this class use positive integers as sizes, * with INF indicating positive infinity. This picks up accidental addition or * subtraction from infinity. * * @param toCheck integer to validate * @since 3.1 */ static void AssertValidSize(int toCheck); /** * Computes the preferred size for this object. The interpretation of the result depends on the flags returned * by getSizeFlags(). If the caller is looking for a maximum or minimum size, this delegates to computeMinimumSize * or computeMaximumSize in order to benefit from caching optimizations. Otherwise, it delegates to * doComputePreferredSize. Subclasses should overload one of doComputeMinimumSize, doComputeMaximumSize, or * doComputePreferredSize to specialize the return value. * * @see LayoutPart#computePreferredSize(boolean, int, int, int) */ int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); protected: /** * Returns the size flags for this tree. * * @see org.blueberry.ui.presentations.StackPresentation#getSizeFlags(boolean) * * @param b indicates whether the caller wants the flags for computing widths (=true) or heights (=false) * @return a bitwise combiniation of flags with the same meaning as StackPresentation.getSizeFlags(boolean) */ virtual int DoGetSizeFlags(bool width); /** * Subclasses should overload this method instead of computePreferredSize(boolean, int, int, int) * * @see org.blueberry.ui.presentations.StackPresentation#computePreferredSize(boolean, int, int, int) * * @since 3.1 */ virtual int DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: /** * Returns the minimum size for this subtree. Equivalent to calling * computePreferredSize(width, INF, availablePerpendicular, 0). * Returns a cached value if possible or defers to doComputeMinimumSize otherwise. * Subclasses should overload doComputeMinimumSize if they want to specialize the * return value. * * @param width true iff computing the minimum width, false iff computing the minimum height * @param availablePerpendicular available space (pixels) perpendicular to the dimension * being computed. This is a height when computing a width, or a width when computing a height. * * @see LayoutPart#computePreferredSize(boolean, int, int, int) */ int ComputeMinimumSize(bool width, int availablePerpendicular); /** * For use in benchmarks and test suites only. Displays cache utilization statistics for all * LayoutTree instances. * * @since 3.1 */ static void PrintCacheStatistics(); virtual int DoComputeMinimumSize(bool width, int availablePerpendicular); int ComputeMaximumSize(bool width, int availablePerpendicular); protected: virtual int DoComputeMaximumSize(bool width, int availablePerpendicular); public: /** * Called to flush any cached information in this tree and its parents. */ virtual void FlushNode(); /** * Flushes all cached information about this node and all of its children. * This should be called if something may have caused all children to become * out of synch with their cached information (for example, if a lot of changes * may have happened without calling flushCache after each change) * * @since 3.1 */ virtual void FlushChildren(); /** * Flushes all cached information about this node and all of its ancestors. * This should be called when a single child changes. * * @since 3.1 */ void FlushCache(); int GetSizeFlags(bool width); /** * Returns the parent of this tree or null if it is the root. */ virtual LayoutTreeNode* GetParent() const; /** * Inserts a new child on the tree. The child will be placed beside * the relative child. Returns the new root of the tree. */ virtual SmartPointer Insert(LayoutPart::Pointer child, bool left, SmartPointer sash, SmartPointer relative); /** * Returns true if this tree can be compressed and expanded. * @return true if springy */ virtual bool IsCompressible(); /** * Returns true if this tree has visible parts otherwise returns false. */ virtual bool IsVisible(); /** * Recompute the ratios in this tree. */ virtual void RecomputeRatio(); /** * Find a child in the tree and remove it and its parent. * The other child of its parent is placed on the parent's parent. * Returns the new root of the tree. */ virtual SmartPointer Remove(LayoutPart::Pointer child); /** * Sets the bounds of this node. If the bounds have changed or any children have * changed then the children will be recursively layed out. This implementation * filters out redundant calls and delegates to doSetBounds to layout the children. * Subclasses should overload doSetBounds to lay out their children. * * @param bounds new bounds of the tree */ - void SetBounds(const Rectangle& bounds); + void SetBounds(const QRect& bounds); protected: /** * Resize the parts on this tree to fit in bounds. */ - virtual void DoSetBounds(const Rectangle& bounds); + virtual void DoSetBounds(const QRect& bounds); public: /** * Set the parent of this tree. */ virtual void SetParent(LayoutTreeNode* parent); /** * Set the part of this leaf */ virtual void SetPart(LayoutPart::Pointer part); /** * Returns a string representation of this object. */ virtual QString ToString() const; /** * Creates SWT controls owned by the LayoutTree (ie: the sashes). Does not affect the * LayoutParts that are being arranged by the LayoutTree. * * @param parent * @since 3.1 */ virtual void CreateControl(void* parent); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. *

* This is only intended for use by test suites. *

* * @param buf */ virtual void DescribeLayout(QString& buf) const; /** * This is a shorthand method that checks if the tree contains the * given size flag. For example, hasSizeFlag(false, SWT.MIN) returns * true iff the receiver enforces a minimum height, or * hasSizeFlag(true, SWT.WRAP) returns true iff the receiver needs to * know its height when computing its preferred width. * * @param vertical * @return * @since 3.1 */ bool HasSizeFlag(bool width, int flag); }; } #endif /*BERRYLAYOUTTREE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp index fa15915437..2193b84808 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp @@ -1,719 +1,723 @@ /*=================================================================== 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 "berryLayoutTreeNode.h" #include "berryConstants.h" #include "berryIPageLayout.h" #include namespace berry { LayoutTreeNode::ChildSizes::ChildSizes (int l, int r, bool resize) { left = l; right = r; resizable = resize; } LayoutTreeNode::LayoutTreeNode(LayoutPartSash::Pointer sash) : LayoutTree(sash) { children[0] = 0; children[1] = 0; } LayoutTreeNode::~LayoutTreeNode() { } void LayoutTreeNode::FlushChildren() { LayoutTree::FlushChildren(); children[0]->FlushChildren(); children[1]->FlushChildren(); } -LayoutPart::Pointer LayoutTreeNode::FindPart(const Point& toFind) +LayoutPart::Pointer LayoutTreeNode::FindPart(const QPoint& toFind) { if (!children[0]->IsVisible()) { if (!children[1]->IsVisible()) { return LayoutPart::Pointer(0); } return children[1]->FindPart(toFind); } else { if (!children[1]->IsVisible()) { return children[0]->FindPart(toFind); } } LayoutPartSash::Pointer sash = this->GetSash(); - Rectangle bounds = sash->GetBounds(); + QRect bounds = sash->GetBounds(); if (sash->IsVertical()) { - if (toFind.x < bounds.x + (bounds.width / 2)) + if (toFind.x() < bounds.x() + (bounds.width() / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } else { - if (toFind.y < bounds.y + (bounds.height / 2)) + if (toFind.y() < bounds.y() + (bounds.height() / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } } LayoutPart::Pointer LayoutTreeNode::ComputeRelation( QList& relations) { PartSashContainer::RelationshipInfo r = PartSashContainer::RelationshipInfo(); r.relative = children[0]->ComputeRelation(relations); r.part = children[1]->ComputeRelation(relations); r.left = this->GetSash()->GetLeft(); r.right = this->GetSash()->GetRight(); r.relationship = this->GetSash()->IsVertical() ? IPageLayout::RIGHT : IPageLayout::BOTTOM; relations.push_front(r); return r.relative; } void LayoutTreeNode::DisposeSashes() { children[0]->DisposeSashes(); children[1]->DisposeSashes(); this->GetSash()->Dispose(); } LayoutTree::Pointer LayoutTreeNode::Find(LayoutPart::Pointer child) { LayoutTree::Pointer node = children[0]->Find(child); if (node != 0) { return node; } node = children[1]->Find(child); return node; } LayoutPart::Pointer LayoutTreeNode::FindBottomRight() { if (children[1]->IsVisible()) { return children[1]->FindBottomRight(); } return children[0]->FindBottomRight(); } LayoutTreeNode* LayoutTreeNode::FindCommonParent(LayoutPart::Pointer child1, LayoutPart::Pointer child2, bool foundChild1, bool foundChild2) { if (!foundChild1) { foundChild1 = this->Find(child1) != 0; } if (!foundChild2) { foundChild2 = this->Find(child2) != 0; } if (foundChild1 && foundChild2) { return this; } if (parent == 0) { return 0; } return parent ->FindCommonParent(child1, child2, foundChild1, foundChild2); } LayoutTreeNode::Pointer LayoutTreeNode::FindSash(LayoutPartSash::Pointer sash) { if (this->GetSash() == sash) { return LayoutTreeNode::Pointer(this); } LayoutTreeNode::Pointer node = children[0]->FindSash(sash); if (node != 0) { return node; } node = children[1]->FindSash(sash); if (node != 0) { return node; } return LayoutTreeNode::Pointer(0); } void LayoutTreeNode::FindSashes(LayoutTree::Pointer child, PartPane::Sashes sashes) { void* sash = this->GetSash()->GetControl(); bool leftOrTop = children[0] == child; if (sash != 0) { LayoutPartSash::Pointer partSash = this->GetSash(); //If the child is in the left, the sash //is in the rigth and so on. if (leftOrTop) { if (partSash->IsVertical()) { if (sashes.right == 0) { sashes.right = sash; } } else { if (sashes.bottom == 0) { sashes.bottom = sash; } } } else { if (partSash->IsVertical()) { if (sashes.left == 0) { sashes.left = sash; } } else { if (sashes.top == 0) { sashes.top = sash; } } } } if (this->GetParent() != 0) { this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes); } } LayoutPartSash::Pointer LayoutTreeNode::GetSash() const { return part.Cast(); } int LayoutTreeNode::GetSashSize() const { return this->GetSash()->GetSashSize(); } bool LayoutTreeNode::IsVisible() { return children[0]->IsVisible() || children[1]->IsVisible(); } LayoutTree::Pointer LayoutTreeNode::Remove(LayoutTree::Pointer child) { this->GetSash()->Dispose(); if (parent == 0) { //This is the root. Return the other child to be the new root. if (children[0] == child) { children[1]->SetParent(0); return children[1]; } children[0]->SetParent(0); return children[0]; } LayoutTreeNode::Pointer oldParent(parent); if (children[0] == child) { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[1]); } else { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[0]); } return oldParent; } void LayoutTreeNode::ReplaceChild(LayoutTree::Pointer oldChild, LayoutTree::Pointer newChild) { if (children[0] == oldChild) { children[0] = newChild; } else if (children[1] == oldChild) { children[1] = newChild; } newChild->SetParent(this); if (!children[0]->IsVisible() || !children[0]->IsVisible()) { this->GetSash()->Dispose(); } this->FlushCache(); } bool LayoutTreeNode::SameDirection(bool isVertical, LayoutTreeNode::Pointer subTree) { bool treeVertical = this->GetSash()->IsVertical(); if (treeVertical != isVertical) { return false; } while (subTree != 0) { if (this == subTree.GetPointer()) { return true; } if (subTree->children[0]->IsVisible() && subTree->children[1]->IsVisible()) { if (subTree->GetSash()->IsVertical() != isVertical) { return false; } } subTree = subTree->GetParent(); } return true; } int LayoutTreeNode::DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { this->AssertValidSize(availablePerpendicular); this->AssertValidSize(availableParallel); this->AssertValidSize(preferredParallel); // If one child is invisible, defer to the other child if (!children[0]->IsVisible()) { return children[1]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (!children[1]->IsVisible()) { return children[0]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (availableParallel == 0) { return 0; } // If computing the dimension perpendicular to our sash if (width == this->GetSash()->IsVertical()) { // Compute the child sizes ChildSizes sizes = this->ComputeChildSizes(availableParallel, availablePerpendicular, GetSash()->GetLeft(), GetSash()->GetRight(), preferredParallel); // Return the sum of the child sizes plus the sash size return this->Add(sizes.left, this->Add(sizes.right, this->GetSashSize())); } else { // Computing the dimension parallel to the sash. We will compute and return the preferred size // of whichever child is closest to the ideal size. // First compute the dimension of the child sizes perpendicular to the sash ChildSizes sizes = this->ComputeChildSizes(availablePerpendicular, availableParallel, GetSash()->GetLeft(), GetSash()->GetRight(), availablePerpendicular); // Use this information to compute the dimension of the child sizes parallel to the sash. // Return the preferred size of whichever child is largest int leftSize = children[0]->ComputePreferredSize(width, availableParallel, sizes.left, preferredParallel); // Compute the preferred size of the right child int rightSize = children[1]->ComputePreferredSize(width, availableParallel, sizes.right, preferredParallel); // Return leftSize or rightSize: whichever one is largest int result = rightSize; if (leftSize > rightSize) { result = leftSize; } this->AssertValidSize(result); return result; } } LayoutTreeNode::ChildSizes LayoutTreeNode::ComputeChildSizes(int width, int height, int left, int right, int preferredWidth) { poco_assert(children[0]->IsVisible()); poco_assert(children[1]->IsVisible()); this->AssertValidSize(width); this->AssertValidSize(height); this->AssertValidSize(preferredWidth); poco_assert(left >= 0); poco_assert(right >= 0); poco_assert(preferredWidth >= 0); poco_assert(preferredWidth <= width); bool vertical = this->GetSash()->IsVertical(); if (width <= this->GetSashSize()) { return ChildSizes(0,0, false); } if (width == INF) { if (preferredWidth == INF) { return ChildSizes(children[0]->ComputeMaximumSize(vertical, height), children[1]->ComputeMaximumSize(vertical, height), false); } if (preferredWidth == 0) { return ChildSizes(children[0]->ComputeMinimumSize(vertical, height), children[1]->ComputeMinimumSize(vertical, height), false); } } int total = left + right; // Use all-or-none weighting double wLeft = left, wRight = right; switch (this->GetCompressionBias()) { case -1: wLeft = 0.0; break; case 1: wRight = 0.0; break; default: break; } double wTotal = wLeft + wRight; // Subtract the SASH_WIDTH from preferredWidth and width. From here on, we'll deal with the // width available to the controls and neglect the space used by the sash. preferredWidth = std::max(0, this->Subtract(preferredWidth, this->GetSashSize())); width = std::max(0, this->Subtract(width, this->GetSashSize())); int redistribute = this->Subtract(preferredWidth, total); // Compute the minimum and maximum sizes for each child int leftMinimum = children[0]->ComputeMinimumSize(vertical, height); int rightMinimum = children[1]->ComputeMinimumSize(vertical, height); int leftMaximum = children[0]->ComputeMaximumSize(vertical, height); int rightMaximum = children[1]->ComputeMaximumSize(vertical, height); int idealLeft = 0; int idealRight = 0; if (PartSashContainer::leftToRight) { // Keep track of the available space for each child, given the minimum size of the other child int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); // Figure out the ideal size of the left child idealLeft = std::max(leftMinimum, std::min(preferredWidth, left + (int)(redistribute * wLeft / wTotal))); // If the right child can't use all its available space, let the left child fill it in idealLeft = std::max(idealLeft, preferredWidth - rightAvailable); // Ensure the left child doesn't get larger than its available space idealLeft = std::min(idealLeft, leftAvailable); // Check if the left child would prefer to be a different size idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); // Ensure that the left child is larger than its minimum size idealLeft = std::max(idealLeft, leftMinimum); idealLeft = std::min(idealLeft, leftAvailable); // Compute the right child width idealRight = std::max(rightMinimum, preferredWidth - idealLeft); rightAvailable = std::max(0, std::min(rightAvailable, this->Subtract(width, idealLeft))); idealRight = std::min(idealRight, rightAvailable); idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); idealRight = std::max(idealRight, rightMinimum); } else { // Keep track of the available space for each child, given the minimum size of the other child int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); // Figure out the ideal size of the right child idealRight = std::max(rightMinimum, std::min(preferredWidth, right + (int)(redistribute * wRight / wTotal))); // If the left child can't use all its available space, let the right child fill it in idealRight = std::max(idealRight, preferredWidth - leftAvailable); // Ensure the right child doesn't get larger than its available space idealRight = std::min(idealRight, rightAvailable); // Check if the right child would prefer to be a different size idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); // Ensure that the right child is larger than its minimum size idealRight = std::max(idealRight, rightMinimum); idealRight = std::min(idealRight, rightAvailable); // Compute the left child width idealLeft = std::max(leftMinimum, preferredWidth - idealRight); leftAvailable = std::max(0, std::min(leftAvailable, this->Subtract(width, idealRight))); idealLeft = std::min(idealLeft, leftAvailable); idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); idealLeft = std::max(idealLeft, leftMinimum); } return ChildSizes(idealLeft, idealRight, leftMaximum> leftMinimum && rightMaximum> rightMinimum && leftMinimum + rightMinimum < width); } int LayoutTreeNode::DoGetSizeFlags(bool width) { if (!children[0]->IsVisible()) { return children[1]->GetSizeFlags(width); } if (!children[1]->IsVisible()) { return children[0]->GetSizeFlags(width); } int leftFlags = children[0]->GetSizeFlags(width); int rightFlags = children[1]->GetSizeFlags(width); return ((leftFlags | rightFlags) & ~Constants::MAX) | (leftFlags & rightFlags & Constants::MAX); } -void LayoutTreeNode::DoSetBounds(const Rectangle& b) +void LayoutTreeNode::DoSetBounds(const QRect& b) { if (!children[0]->IsVisible()) { children[1]->SetBounds(b); this->GetSash()->SetVisible(false); return; } if (!children[1]->IsVisible()) { children[0]->SetBounds(b); this->GetSash()->SetVisible(false); return; } - Rectangle bounds = b; + QRect bounds = b; bool vertical = this->GetSash()->IsVertical(); // If this is a horizontal sash, flip coordinate systems so // that we can eliminate special cases if (!vertical) { - bounds.FlipXY(); + bounds = FlipRect(bounds); } - ChildSizes childSizes = this->ComputeChildSizes(bounds.width, bounds.height, - this->GetSash()->GetLeft(), this->GetSash()->GetRight(), bounds.width); + ChildSizes childSizes = this->ComputeChildSizes(bounds.width(), bounds.height(), + this->GetSash()->GetLeft(), this->GetSash()->GetRight(), bounds.width()); this->GetSash()->SetVisible(true); this->GetSash()->SetEnabled(childSizes.resizable); - Rectangle leftBounds = Rectangle(bounds.x, bounds.y, childSizes.left, bounds.height); - Rectangle sashBounds = Rectangle(leftBounds.x + leftBounds.width, bounds.y, this->GetSashSize(), bounds.height); - Rectangle - rightBounds = - Rectangle(sashBounds.x + sashBounds.width, bounds.y, childSizes.right, bounds.height); + QRect leftBounds = QRect(bounds.x(), bounds.y(), childSizes.left, bounds.height()); + QRect sashBounds = QRect(leftBounds.x() + leftBounds.width(), bounds.y(), this->GetSashSize(), bounds.height()); + QRect rightBounds = QRect(sashBounds.x() + sashBounds.width(), bounds.y(), + childSizes.right, bounds.height()); if (!vertical) { - leftBounds.FlipXY(); - sashBounds.FlipXY(); - rightBounds.FlipXY(); + leftBounds = FlipRect(leftBounds); + sashBounds = FlipRect(sashBounds); + rightBounds = FlipRect(rightBounds); } this->GetSash()->SetBounds(sashBounds); children[0]->SetBounds(leftBounds); children[1]->SetBounds(rightBounds); } void LayoutTreeNode::CreateControl(void* parent) { children[0]->CreateControl(parent); children[1]->CreateControl(parent); this->GetSash()->CreateControl(parent); LayoutTree::CreateControl(parent); } bool LayoutTreeNode::IsCompressible() { return children[0]->IsCompressible() || children[1]->IsCompressible(); } int LayoutTreeNode::GetCompressionBias() { bool left = children[0]->IsCompressible(); bool right = children[1]->IsCompressible(); if (left == right) { return 0; } if (right) { return -1; } return 1; } bool LayoutTreeNode::IsLeftChild(LayoutTree::ConstPointer toTest) { return children[0] == toTest; } LayoutTree::Pointer LayoutTreeNode::GetChild(bool left) { int index = left ? 0 : 1; return (children[index]); } void LayoutTreeNode::SetChild(bool left, LayoutPart::Pointer part) { LayoutTree::Pointer child(new LayoutTree(part)); this->SetChild(left, child); this->FlushCache(); } void LayoutTreeNode::SetChild(bool left, LayoutTree::Pointer child) { int index = left ? 0 : 1; children[index] = child; child->SetParent(this); this->FlushCache(); } QString LayoutTreeNode::ToString() const { QString str; QTextStream s(&str); s << "\n"; if (part->GetControl() != 0) { s << "<@" << part->GetControl() << ">\n"; } QString str2; QTextStream result(&str2); result << "["; if (children[0]->GetParent() != this) { result << str2 << "{" << children[0] << "}" << str; } else { result << str2 << children[0] << str; } if (children[1]->GetParent() != this) { result << str2 << "{" << children[1] << "}]"; } else { result << str2 << children[1] << "]"; } return str2; } //void LayoutTreeNode::UpdateSashes(void* parent) { // if (parent == 0) // return; // children[0]->UpdateSashes(parent); // children[1]->UpdateSashes(parent); // if (children[0]->IsVisible() && children[1]->IsVisible()) // this->GetSash()->CreateControl(parent); // else // this->GetSash()->Dispose(); // } void LayoutTreeNode::DescribeLayout(QString& buf) const { if (!(children[0]->IsVisible())) { if (!children[1]->IsVisible()) { return; } children[1]->DescribeLayout(buf); return; } if (!children[1]->IsVisible()) { children[0]->DescribeLayout(buf); return; } buf.append("("); //$NON-NLS-1$ children[0]->DescribeLayout(buf); buf.append(this->GetSash()->IsVertical() ? "|" : "-"); children[1]->DescribeLayout(buf); buf.append(")"); } +QRect LayoutTreeNode::FlipRect(const QRect& rect) +{ + return QRect(rect.y(), rect.x(), rect.height(), rect.width()); +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h index 2f2dc90cd3..65baa5a47b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h @@ -1,226 +1,229 @@ /*=================================================================== 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 BERRYLAYOUTTREENODE_H_ #define BERRYLAYOUTTREENODE_H_ #include "berryLayoutTree.h" #include "berryLayoutPartSash.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Implementation of a tree node. The node represents a * sash and it allways has two children. */ class LayoutTreeNode : public LayoutTree { public: berryObjectMacro(LayoutTreeNode) struct ChildSizes { int left; int right; bool resizable; ChildSizes (int l, int r, bool resize); }; /* The node children witch may be another node or a leaf */ private: LayoutTree::Pointer children[2]; /** * Initialize this tree with its sash. */ public: LayoutTreeNode(LayoutPartSash::Pointer sash); public: ~LayoutTreeNode(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutTree#flushChildren() */ public: void FlushChildren(); /** * Traverses the tree to find the part that intersects the given point * * @param toFind * @return the part that intersects the given point */ - public: LayoutPart::Pointer FindPart(const Point& toFind); + public: LayoutPart::Pointer FindPart(const QPoint& toFind); /** * Add the relation ship between the children in the list * and returns the left children. */ public: LayoutPart::Pointer ComputeRelation(QList& relations); /** * Dispose all Sashs in this tree */ public: void DisposeSashes(); /** * Find a LayoutPart in the tree and return its sub-tree. Returns * null if the child is not found. */ public: SmartPointer Find(LayoutPart::Pointer child); /** * Find the part that is in the bottom right position. */ public: LayoutPart::Pointer FindBottomRight(); /** * Go up in the tree finding a parent that is common of both children. * Return the subtree. */ LayoutTreeNode* FindCommonParent(LayoutPart::Pointer child1, LayoutPart::Pointer child2, bool foundChild1 = false, bool foundChild2 = false); /** * Find a sash in the tree and return its sub-tree. Returns * null if the sash is not found. */ public: SmartPointer FindSash(LayoutPartSash::Pointer sash); using LayoutTree::FindSashes; /** * Sets the elements in the array of sashes with the * Left,Rigth,Top and Botton sashes. The elements * may be null depending whether there is a shash * beside the part */ void FindSashes(SmartPointer child, PartPane::Sashes sashes); /** * Returns the sash of this node. */ public: LayoutPartSash::Pointer GetSash() const; private: int GetSashSize() const; /** * Returns true if this tree has visible parts otherwise returns false. */ public: bool IsVisible(); using LayoutTree::Remove; /** * Remove the child and this node from the tree */ SmartPointer Remove(SmartPointer child); /** * Replace a child with a new child and sets the new child's parent. */ void ReplaceChild(SmartPointer oldChild, SmartPointer newChild); /** * Go up from the subtree and return true if all the sash are * in the direction specified by isVertical */ public: bool SameDirection(bool isVertical, SmartPointer subTree); public: int DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /** * Computes the pixel sizes of this node's children, given the available * space for this node. Note that "width" and "height" actually refer * to the distance perpendicular and parallel to the sash respectively. * That is, their meaning is reversed when computing a horizontal sash. * * @param width the pixel width of a vertical node, or the pixel height * of a horizontal node (INF if unbounded) * @param height the pixel height of a vertical node, or the pixel width * of a horizontal node (INF if unbounded) * @return a struct describing the pixel sizes of the left and right children * (this is a width for horizontal nodes and a height for vertical nodes) */ ChildSizes ComputeChildSizes(int width, int height, int left, int right, int preferredWidth); protected: int DoGetSizeFlags(bool width); /** * Resize the parts on this tree to fit in bounds. */ - public: void DoSetBounds(const Rectangle& bounds); + public: void DoSetBounds(const QRect& bounds); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutTree#createControl(org.blueberry.swt.widgets.Composite) */ public: void CreateControl(void* parent); //Added by hudsonr@us.ibm.com - bug 19524 public: bool IsCompressible(); /** * Returns 0 if there is no bias. Returns -1 if the first child should be of * fixed size, and the second child should be compressed. Returns 1 if the * second child should be of fixed size. * @return the bias */ public: int GetCompressionBias(); bool IsLeftChild(SmartPointer toTest); SmartPointer GetChild(bool left); /** * Sets a child in this node */ void SetChild(bool left, LayoutPart::Pointer part); /** * Sets a child in this node */ void SetChild(bool left, SmartPointer child); /** * Returns a string representation of this object. */ public: QString ToString() const; /** * Create the sashes if the children are visible * and dispose it if they are not. */ //public: void UpdateSashes(void* parent); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. * * @param buf */ public: void DescribeLayout(QString& buf) const; +private: + + static QRect FlipRect(const QRect& rect); }; } #endif /*BERRYLAYOUTTREENODE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp index 4528612f65..d7bab9d5ed 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp @@ -1,464 +1,464 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryPartPane.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartStack.h" #include "berryEditorAreaHelper.h" #include "berryPerspective.h" #include "berryPartStack.h" #include "berryDragUtil.h" namespace berry { PartPane::Sashes::Sashes() : left(0), right(0), top(0), bottom(0) { } PartPane::PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage) : LayoutPart(partReference->GetId()), control(0), inLayout(true), busy(false), hasFocus(false) { //super(partReference.getId()); this->partReference = partReference; this->page = workbenchPage; } void PartPane::CreateControl(void* parent) { if (this->GetControl() != 0) { return; } partReference.Lock()->AddPropertyListener(this); // Create view form. control = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreatePaneControl(parent); // the part should never be visible by default. It will be made visible // by activation. This allows us to have views appear in tabs without // becoming active by default. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(control, false); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(control, 0); // Create a title bar. //this->CreateTitleBar(); // When the pane or any child gains focus, notify the workbench. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(control, GuiTk::IControlListener::Pointer(this)); //control.addTraverseListener(traverseListener); } PartPane::~PartPane() { // super.dispose(); // this->Register(); if (control != 0) { BERRY_DEBUG << "Deleting PartPane control"; Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(control, GuiTk::IControlListener::Pointer(this)); // control.removeTraverseListener(traverseListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(control); control = 0; } // if ((paneMenuManager != null)) // { // paneMenuManager.dispose(); // paneMenuManager = null; // } // if (!partReference.Expired()) { partReference.Lock()->RemovePropertyListener(this); } // partReference.removePartPropertyListener(this); this->UnRegister(false); } void PartPane::DoHide() { if (partReference.Lock().Cast() != 0) { this->GetPage()->HideView(partReference.Lock().Cast()); } else if (partReference.Lock().Cast() != 0) { this->GetPage()->CloseEditor(partReference.Lock().Cast(), true); } } -Rectangle PartPane::GetParentBounds() +QRect PartPane::GetParentBounds() { void* ctrl = this->GetControl(); if (this->GetContainer() != 0 && this->GetContainer().Cast() != 0) { LayoutPart::Pointer part = this->GetContainer().Cast(); if (part->GetControl() != 0) { ctrl = part->GetControl(); } } return DragUtil::GetDisplayBounds(ctrl); } void* PartPane::GetControl() { return control; } IWorkbenchPartReference::Pointer PartPane::GetPartReference() const { return partReference.Lock(); } void PartPane::ControlActivated(GuiTk::ControlEvent::Pointer /*e*/) { if (inLayout) { this->RequestActivation(); } } GuiTk::IControlListener::Events::Types PartPane::GetEventTypes() const { return GuiTk::IControlListener::Events::ACTIVATED; } void PartPane::MoveAbove(void* refControl) { if (this->GetControl() != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(this->GetControl(), refControl); } } void PartPane::RequestActivation() { IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); this->page->RequestActivation(part); } //PartStack::Pointer PartPane::GetStack() //{ // return partStack; //} PartPane::Sashes PartPane::FindSashes() { Sashes result; ILayoutContainer::Pointer container = this->GetContainer(); if (container == 0) { return result; } container->FindSashes(LayoutPart::Pointer(this), result); return result; } WorkbenchPage::Pointer PartPane::GetPage() { return WorkbenchPage::Pointer(page); } void PartPane::SetContainer(ILayoutContainer::Pointer container) { if (hasFocus) { ILayoutContainer::Pointer oldContainer = this->GetContainer(); if (PartStack::Pointer oldStack = oldContainer.Cast()) { oldStack->SetActive(StackPresentation::AS_INACTIVE); } if (PartStack::Pointer newContainer = container.Cast()) { newContainer->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } } void* containerControl = container == 0 ? 0 : container.Cast()->GetControl(); if (containerControl != 0) { void* control = this->GetControl(); void* newParent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(containerControl); if (control != 0 && newParent != Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(control)) { this->Reparent(newParent); } } LayoutPart::SetContainer(container); } void PartPane::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void PartPane::ShowFocus(bool inFocus) { if (partReference.Lock().Cast() != 0) { hasFocus = inFocus; } if (PartStack::Pointer stack = this->GetContainer().Cast()) { if (partReference.Lock().Cast() != 0) { stack->SetActive(inFocus ? StackPresentation::AS_ACTIVE_FOCUS : StackPresentation::AS_INACTIVE); } else if (partReference.Lock().Cast() != 0) { if (inFocus) { page->GetEditorPresentation()->SetActiveWorkbook(stack, true); } else { stack->SetActive(page->GetEditorPresentation()->GetActiveWorkbook() == stack ? StackPresentation::AS_ACTIVE_NOFOCUS : StackPresentation::AS_INACTIVE); } } } } PartStack::Pointer PartPane::GetStack() { ILayoutContainer::Pointer container = this->GetContainer(); return container.Cast(); } void PartPane::SetVisible(bool makeVisible) { // Avoid redundant visibility changes if (makeVisible == this->GetVisible()) { return; } if (makeVisible) { partReference.Lock()->GetPart(true); } if (this->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(this->GetControl(), makeVisible); partReference.Lock().Cast()->FireVisibilityChange(); } bool PartPane::GetVisible() { if (this->GetControl() != 0) return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(this->GetControl()); return false; } void PartPane::SetFocus() { this->RequestActivation(); IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); if (part.IsNotNull()) { // Control control = getControl(); // if (!SwtUtil.isFocusAncestor(control)) // { // First try to call part.setFocus part->SetFocus(); //} } } void PartPane::SetWorkbenchPage(WorkbenchPage::Pointer workbenchPage) { this->page = workbenchPage.GetPointer(); } void PartPane::DoDock() { // do nothing } void PartPane::SetBusy(bool isBusy) { if (isBusy != busy) { busy = isBusy; //firePropertyChange(IPresentablePart.PROP_BUSY); } } void PartPane::ShowHighlight() { //No nothing by default } void* PartPane::GetToolBar() { return 0; } bool PartPane::HasViewMenu() { return false; } bool PartPane::IsBusy() { return busy; } void PartPane::DescribeLayout(QString& buf) const { IWorkbenchPartReference::Pointer part = this->GetPartReference(); if (part.IsNotNull()) { buf.append(part->GetPartName()); return; } } bool PartPane::IsCloseable() { if (partReference.Lock().Cast() != 0) { Perspective::Pointer perspective = page->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } return perspective->IsCloseable(partReference.Lock().Cast()); } return true; } void PartPane::SetInLayout(bool inLayout) { this->inLayout = inLayout; } bool PartPane::GetInLayout() { return inLayout; } bool PartPane::AllowsAutoFocus() { if (!inLayout) { return false; } //return super.allowsAutoFocus(); return true; } void PartPane::RemoveContributions() { } void PartPane::AddPropertyListener(IPropertyChangeListener *listener) { propertyChangeEvents.AddListener(listener); } void PartPane::RemovePropertyListener(IPropertyChangeListener *listener) { propertyChangeEvents.RemoveListener(listener); } void PartPane::FirePropertyChange(const PropertyChangeEvent::Pointer& event) { propertyChangeEvents.propertyChange(event); } void PartPane::PropertyChange(const PropertyChangeEvent::Pointer& event) { this->FirePropertyChange(event); } int PartPane::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return partReference.Lock().Cast()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartPane::GetSizeFlags(bool horizontal) { return partReference.Lock().Cast()->GetSizeFlags(horizontal); } void PartPane::ShellActivated() { } void PartPane::ShellDeactivated() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h index 0dcb80ac98..181bb7cf83 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h @@ -1,437 +1,436 @@ /*=================================================================== 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 BERRYPARTPANE_H_ #define BERRYPARTPANE_H_ #include "berryWorkbenchPartReference.h" #include "berryLayoutPart.h" -#include "berryRectangle.h" #include "berryIPropertyChangeListener.h" #include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartStack; struct ILayoutContainer; /** * Provides the common behavior for both views * and editor panes. * */ class PartPane : public LayoutPart, public IPropertyChangeListener, public GuiTk::IControlListener { public: berryObjectMacro(PartPane) friend class PartSashContainer; friend class EditorSashContainer; friend class WorkbenchPage; friend struct ILayoutContainer; friend class PartStack; friend class ContainerPlaceholder; friend class LayoutTree; friend class LayoutTreeNode; friend class DetachedPlaceHolder; friend class PerspectiveHelper; // private: MenuManager paneMenuManager; // private: ListenerList listeners = new ListenerList(); // private: ListenerList partListeners = new ListenerList(); private: IPropertyChangeListener::Events propertyChangeEvents; protected: IWorkbenchPartReference::WeakPtr partReference; protected: WorkbenchPage* page; protected: void* control; private: bool inLayout; // private: TraverseListener traverseListener = new TraverseListener() { // /* (non-Javadoc) // * @see org.blueberry.swt.events.TraverseListener#keyTraversed(org.blueberry.swt.events.TraverseEvent) // */ // public: void keyTraversed(TraverseEvent e) { // // Hack: Currently, SWT sets focus whenever we call Control.traverse. This doesn't // // cause too much of a problem for ctrl-pgup and ctrl-pgdn, but it is seriously unexpected // // for other traversal events. When (and if) it becomes possible to call traverse() without // // forcing a focus change, this if statement should be removed and ALL events should be // // forwarded to the container. // if (e.detail == SWT.TRAVERSE_PAGE_NEXT // || e.detail == SWT.TRAVERSE_PAGE_PREVIOUS) { // ILayoutContainer container = getContainer(); // if (container != null && container instanceof LayoutPart) { // LayoutPart parent = (LayoutPart) container; // Control parentControl = parent.getControl(); // if (parentControl != null && !parentControl.isDisposed()) { // e.doit = parentControl.traverse(e.detail); // if (e.doit) { // e.detail = SWT.TRAVERSE_NONE; // } // } // } // } // } // // }; private: bool busy; private: bool hasFocus; //private: SmartPointer partStack; protected: /*static*/ class Sashes { public: Sashes(); /*Sash*/ void* left; /*Sash*/ void* right; /*Sash*/ void* top; /*Sash*/ void* bottom; }; /** * Construct a pane for a part. */ public: PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage); // public: void addSizeMenuItem(Menu menu, int index) { // //Add size menu // MenuItem item = new MenuItem(menu, SWT.CASCADE, index); // item.setText(WorkbenchMessages.PartPane_size); // Menu sizeMenu = new Menu(menu); // item.setMenu(sizeMenu); // addSizeItems(sizeMenu); // } /** * * Creates the GUI-dependent container control * for the part widgets. This is passed to * IWorkbenchPart::CreatePartControl(void*) */ public: virtual void CreateControl(void* parent); //public: virtual void SetControlEnabled(bool enabled) = 0; /** * Create a title bar for the pane if required. */ // protected: virtual void CreateTitleBar() = 0; /** * @private: */ public: virtual ~PartPane(); /** * User has requested to close the pane. * Take appropriate action depending on type. */ public: void DoHide(); - protected: Rectangle GetParentBounds(); + protected: QRect GetParentBounds(); /** * Get the control. */ public: void* GetControl(); /** * Answer the part child. */ public: IWorkbenchPartReference::Pointer GetPartReference() const; /** * @see GuiTk::IControlListener */ public: void ControlActivated(GuiTk::ControlEvent::Pointer e); /** * @see GuiTk::IControlListener */ public: GuiTk::IControlListener::Events::Types GetEventTypes() const; /** * Move the control over another one. */ public: void MoveAbove(void* refControl); /** * Notify the workbook page that the part pane has * been activated by the user. */ public: void RequestActivation(); /** * Shows the receiver if visible is true otherwise hide it. */ public: void SetVisible(bool makeVisible); public: virtual bool GetVisible(); /** * Sets focus to this part. */ public: void SetFocus(); /** * Sets the workbench page of the view. */ public: void SetWorkbenchPage(SmartPointer workbenchPage); public: void Reparent(void* newParent); /** * Indicate focus in part. */ public: void ShowFocus(bool inFocus); /** * @see IPartDropTarget::targetPartFor */ // public: LayoutPart targetPartFor(LayoutPart dragSource) { // return this; // } /** * Returns the PartStack that contains this PartPane, or null if none. * * @return */ public: SmartPointer GetStack(); public: void SetContainer(SmartPointer stack); /** * Show a title label menu for this pane. */ // public: void ShowPaneMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showPaneMenu(); // } // } /** * Show the context menu for this part. */ // public: void showSystemMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showSystemMenu(); // } // } /** * Finds and return the sashes around this part. */ protected: Sashes FindSashes(); /** * Enable the user to resize this part using * the keyboard to move the specified sash */ // protected: void moveSash(final Sash sash) { // moveSash(sash, this); // } // public: static void moveSash(final Sash sash, // final LayoutPart toGetFocusWhenDone) { // final KeyListener listener = new KeyAdapter() { // public: void keyPressed(KeyEvent e) { // if (e.character == SWT.ESC || e.character == '\r') { // if (toGetFocusWhenDone != null) { // toGetFocusWhenDone.setFocus(); // } // } // } // }; // sash.addFocusListener(new FocusAdapter() { // public: void focusGained(FocusEvent e) { // sash.setBackground(sash.getDisplay().getSystemColor( // SWT.COLOR_LIST_SELECTION)); // sash.addKeyListener(listener); // } // // public: void focusLost(FocusEvent e) { // sash.setBackground(null); // sash.removeKeyListener(listener); // } // }); // sash.setFocus(); // // } /** * Add a menu item to the Size Menu */ // protected: void addSizeItem(Menu sizeMenu, String labelMessage, // final Sash sash) { // MenuItem item = new MenuItem(sizeMenu, SWT.NONE); // item.setText(labelMessage); // item.addSelectionListener(new SelectionAdapter() { // public: void widgetSelected(SelectionEvent e) { // moveSash(sash); // } // }); // item.setEnabled(!isZoomed() && sash != null); // } /** * Returns the workbench page of this pane. */ public: SmartPointer GetPage(); /** * Add the Left,Right,Up,Botton menu items to the Size menu. */ // protected: void addSizeItems(Menu sizeMenu) { // Sashes sashes = findSashes(); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeLeft, sashes.left); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeRight, sashes.right); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeTop, sashes.top); // addSizeItem(sizeMenu, WorkbenchMessages.PartPane_sizeBottom, sashes.bottom); // } /** * Pin this part. */ protected: virtual void DoDock(); /** * Set the busy state of the pane. */ public: virtual void SetBusy(bool isBusy); /** * Show a highlight for the receiver if it is * not currently the part in the front of its * presentation. * */ public: virtual void ShowHighlight(); /** * @return */ public: virtual void* GetToolBar(); /** * @return */ public: bool HasViewMenu(); /** * @param location */ // public: void ShowViewMenu(Point location) { // // } public: bool IsBusy(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: void DescribeLayout(QString& buf) const; /** * @return * @since 3.1 */ public: bool IsCloseable(); public: void SetInLayout(bool inLayout); public: bool GetInLayout(); public: bool AllowsAutoFocus(); /** * Clears all contribution items from the contribution managers (this is done separately * from dispose() since it is done after the part is disposed). This is a bit of a hack. * Really, the contribution managers should be part of the site, not the PartPane. If these * were moved elsewhere, then disposal of the PartPane would be atomic and this method could * be removed. */ public: virtual void RemoveContributions(); public: void AddPropertyListener(IPropertyChangeListener* listener); public: void RemovePropertyListener(IPropertyChangeListener* listener); public: void FirePropertyChange(const PropertyChangeEvent::Pointer& event); /* (non-Javadoc) * @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent::Pointer) */ public: using IPropertyChangeListener::PropertyChange; void PropertyChange(const PropertyChangeEvent::Pointer& event); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#computePreferredSize(boolean, int, int, int) */ public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getSizeFlags(boolean) */ public: int GetSizeFlags(bool horizontal); /** * Informs the pane that it's window shell has * been activated. */ public: virtual void ShellActivated(); /** * Informs the pane that it's window shell has * been deactivated. */ public: virtual void ShellDeactivated(); }; } #endif /*BERRYPARTPANE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp index 6bf4bd7481..128666fdda 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp @@ -1,1272 +1,1274 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryPartSashContainer.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryPartStack.h" #include "berryPageLayout.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryDragUtil.h" #include "berryWorkbenchPlugin.h" #include "berryIPreferencesService.h" #include "berryIPreferences.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryGeometry.h" #include "berryPartPane.h" +#include "berryQtTracker.h" + #include "berryConstants.h" namespace berry { bool PartSashContainer::leftToRight = true; PartSashContainer::ControlListener::ControlListener( PartSashContainer* container) : partSashContainer(container) { } GuiTk::IControlListener::Events::Types PartSashContainer::ControlListener::GetEventTypes() const { return Events::RESIZED; } void PartSashContainer::ControlListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { partSashContainer->ResizeSashes(); } PartSashContainer::SashContainerDropTarget::SashContainerDropTarget( PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) : partSashContainer(partSashContainer) { this->SetTarget(sourcePart, side, cursor, targetPart); } void PartSashContainer::SashContainerDropTarget::SetTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { this->side = side; this->targetPart = targetPart; this->sourcePart = sourcePart; this->cursor = cursor; } void PartSashContainer::SashContainerDropTarget::Drop() { if (side != Constants::NONE) { LayoutPart::Pointer visiblePart = sourcePart.Cast (); if (sourcePart.Cast () != 0) { visiblePart = partSashContainer->GetVisiblePart(sourcePart.Cast< ILayoutContainer> ()); } partSashContainer->DropObject( partSashContainer->GetVisibleParts(sourcePart), visiblePart, targetPart, side); } } void PartSashContainer::DropObject(const QList& toDrop, LayoutPart::Pointer visiblePart, Object::Pointer targetPart, int side) { //getControl().setRedraw(false); // Targetpart is null if there isn't a part under the cursor (all the parts are // hidden or the container is empty). In this case, the actual side doesn't really // since we'll be the only visible container and will fill the entire space. However, // we can't leave it as Constants::CENTER since we can't stack if we don't have something // to stack on. In this case, we pick Constants::BOTTOM -- this will insert the new pane // below any currently-hidden parts. if (targetPart == 0 && side == Constants::CENTER) { side = Constants::BOTTOM; } PartStack::Pointer targetStack = targetPart.Cast (); if (targetStack == 0 && targetPart.Cast() != 0) { targetStack = targetPart.Cast ()->GetStack(); } LayoutPart::Pointer targetLayoutPart = targetStack; // if targetLayoutPart == 0 then we normally got a EditorSashContainer if (targetLayoutPart == 0) targetLayoutPart = targetPart.Cast(); if (side == Constants::CENTER) { if (this->IsStackType(targetStack)) { for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, targetStack); } } } else { PartStack::Pointer newPart = this->CreateStack(); // if the toDrop array has 1 item propagate the stack // appearance if (toDrop.size() == 1 && toDrop[0]->GetStack() != 0) { toDrop[0]->GetStack()->CopyAppearanceProperties(newPart); } for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, newPart); } this->AddEnhanced(newPart, side, this->GetDockingRatio(newPart, targetStack), targetLayoutPart); } if (visiblePart != 0) { this->SetVisiblePart(visiblePart->GetContainer(), visiblePart.Cast ()); } //getControl().setRedraw(true); if (visiblePart != 0) { visiblePart->SetFocus(); } } -DnDTweaklet::CursorType PartSashContainer::SashContainerDropTarget::GetCursor() +CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { - return DnDTweaklet::PositionToCursorType(cursor); + return QtDragManager::PositionToCursorType(cursor); } -Rectangle PartSashContainer::SashContainerDropTarget::GetSnapRectangle() +QRect PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { - Rectangle targetBounds; + QRect targetBounds; if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else { targetBounds = DragUtil::GetDisplayBounds(partSashContainer->GetParent()); } if (side == Constants::CENTER || side == Constants::NONE) { return targetBounds; } int distance = Geometry::GetDimension(targetBounds, !Geometry::IsHorizontal( side)); ILayoutContainer::Pointer stack = targetPart.Cast (); if (stack == 0 && targetPart.Cast () != 0) { stack = targetPart.Cast ()->GetContainer(); } return Geometry::GetExtrudedEdge(targetBounds, (int) (distance * partSashContainer->GetDockingRatio(sourcePart, stack)), side); } PartSashContainer::PartSashContainer(const QString& id, WorkbenchPage* _page, void* _parentWidget) : LayoutPart(id), parentWidget(_parentWidget), parent(0), page(_page), active( false), layoutDirty(false) { resizeListener = new ControlListener(this); QString layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> GetSystemPreferences()->Get(WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, WorkbenchPreferenceConstants::LEFT); if (layout == WorkbenchPreferenceConstants::RIGHT) { leftToRight = false; } } QList PartSashContainer::GetVisibleParts( Object::Pointer pane) { QList parts; if (pane.Cast ().IsNotNull()) { parts.push_back(pane.Cast ()); } else if (pane.Cast ().IsNotNull()) { PartStack::Pointer stack = pane.Cast (); QList children = stack->GetChildren(); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () != 0) { parts.push_back(iter->Cast ()); } } } return parts; } PartSashContainer::~PartSashContainer() { } void PartSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { if (root == 0) { return; } LayoutTree::Pointer part = root->Find(pane); if (part == 0) { return; } part->FindSashes(sashes); } void PartSashContainer::Add(LayoutPart::Pointer child) { if (child.IsNull()) { return; } this->AddEnhanced(child, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddPart(LayoutPart::Pointer child) { if (child.IsNull()) { return; } PartStack::Pointer newFolder = this->CreateStack(); newFolder->Add(child); this->AddEnhanced(newFolder, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddEnhanced(LayoutPart::Pointer child, int directionConstant, float ratioForNewPart, LayoutPart::Pointer relative) { int relativePosition = PageLayout::ConstantToLayoutPosition(directionConstant); float ratioForUpperLeftPart; if (relativePosition == IPageLayout::RIGHT || relativePosition == IPageLayout::BOTTOM) { ratioForUpperLeftPart = 1.0f - ratioForNewPart; } else { ratioForUpperLeftPart = ratioForNewPart; } this->Add(child, relativePosition, ratioForUpperLeftPart, relative); } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative) { bool isHorizontal = (relationship == IPageLayout::LEFT || relationship == IPageLayout::RIGHT); LayoutTree::Pointer node; if (root != 0 && relative != 0) { node = root->Find(relative); } - Rectangle bounds; + QRect bounds; if (this->GetParent() == 0) { void* control = this->GetPage()->GetClientComposite(); if (control != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { - bounds = Rectangle(0, 0, 800, 600); + bounds = QRect(0, 0, 800, 600); } - bounds.x = 0; - bounds.y = 0; + bounds.setX(0); + bounds.setY(0); } else { bounds = this->GetBounds(); } int totalSize = this->MeasureTree(bounds, node, isHorizontal); int left = (int) (totalSize * ratio); int right = totalSize - left; this->Add(child, relationship, left, right, relative); } -int PartSashContainer::MeasureTree(const Rectangle& outerBounds, +int PartSashContainer::MeasureTree(const QRect& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { - return outerBounds.GetDimension(horizontal); + return Geometry::GetDimension(outerBounds, horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == 0) { - return outerBounds.GetDimension(horizontal); + return Geometry::GetDimension(outerBounds, horizontal); } if (parent->GetSash()->IsHorizontal() == horizontal) { return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } bool isLeft = parent->IsLeftChild(toMeasure); LayoutTree::Pointer otherChild = parent->GetChild(!isLeft); if (otherChild->IsVisible()) { int left = parent->GetSash()->GetLeft(); int right = parent->GetSash()->GetRight(); int childSize = isLeft ? left : right; int bias = parent->GetCompressionBias(); // Normalize bias: 1 = we're fixed, -1 = other child is fixed if (isLeft) { bias = -bias; } if (bias == 1) { // If we're fixed, return the fixed size return childSize; } else if (bias == -1) { // If the other child is fixed, return the size of the parent minus the fixed size of the // other child return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) - (left + right - childSize); } // Else return the size of the parent, scaled appropriately return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) * childSize / (left + right); } return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } void PartSashContainer::AddChild(const RelationshipInfo& info) { LayoutPart::Pointer child = info.part; children.push_back(child); if (root == 0) { root = new LayoutTree(child); } else { //Add the part to the tree. int vertical = (info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::RIGHT) ? Constants::VERTICAL : Constants::HORIZONTAL; bool left = info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::TOP; LayoutPartSash::Pointer sash(new LayoutPartSash(this, vertical)); sash->SetSizes(info.left, info.right); if ((parent != 0) && child.Cast ().IsNull()) { sash->CreateControl(parent); } LayoutTree::Pointer newroot = root->Insert(child, left, sash, info.relative); root = newroot; } this->ChildAdded(child); if (active) { child->CreateControl(parent); child->SetVisible(true); child->SetContainer(ILayoutContainer::Pointer(this)); this->ResizeChild(child); } } void PartSashContainer::AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder) { RelationshipInfo newRelationshipInfo; newRelationshipInfo.part = child; if (root != 0) { newRelationshipInfo.relationship = IPageLayout::RIGHT; newRelationshipInfo.relative = root->FindBottomRight(); newRelationshipInfo.left = 200; newRelationshipInfo.right = 200; } // find the relationship info for the placeholder QList relationships = this->ComputeRelation(); for (int i = 0; i < relationships.size(); i++) { RelationshipInfo info = relationships[i]; if (info.part == placeholder) { newRelationshipInfo.left = info.left; newRelationshipInfo.right = info.right; newRelationshipInfo.relationship = info.relationship; newRelationshipInfo.relative = info.relative; } } this->AddChild(newRelationshipInfo); this->FlushLayout(); } bool PartSashContainer::AllowsBorder() { return true; } void PartSashContainer::ChildAdded(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(true); } } void PartSashContainer::ChildRemoved(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(false); } } QList PartSashContainer::ComputeRelation() { LayoutTree::Pointer treeRoot = root; QList list; if (treeRoot == 0) { return QList(); } RelationshipInfo r; r.part = treeRoot->ComputeRelation(list); list.push_front(r); return list; } void PartSashContainer::SetActive(bool isActive) { if (isActive == active) { return; } active = isActive; ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast ().IsNotNull()) { PartStack::Pointer stack = childIter->Cast (); stack->SetActive(isActive); } } if (isActive) { this->CreateControl(parentWidget); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, resizeListener); DragUtil::AddDragTarget(parent, this); DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer child = *childIter; child->SetContainer(ILayoutContainer::Pointer(this)); child->SetVisible(true); //zoomedPart == null || child == zoomedPart); if (child.Cast ().IsNull()) { if (root != 0) { LayoutTree::Pointer node = root->Find(child); if (node != 0) { node->FlushCache(); } } } } if (root != 0) { //root.flushChildren(); //if (!isZoomed()) { root->CreateControl(parent); } } this->ResizeSashes(); } else { DragUtil::RemoveDragTarget(parent, this); DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); // remove all Listeners if (resizeListener != 0 && parent != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parent, resizeListener); } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; child->SetContainer(ILayoutContainer::Pointer(0)); if (child.Cast ().IsNotNull()) { child->SetVisible(false); } } this->DisposeSashes(); //dispose(); } } void PartSashContainer::CreateControl(void* parentWidget) { if (this->parent != 0) { return; } parent = this->CreateParent(parentWidget); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->CreateControl(parent); } } void PartSashContainer::Dispose() { if (parent == 0) { return; } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { // In PartSashContainer dispose really means deactivate, so we // only dispose PartTabFolders. if (iter->Cast() != 0) { (*iter)->Dispose(); } } this->DisposeParent(); this->parent = 0; } void PartSashContainer::DisposeSashes() { if (root != 0) { root->DisposeSashes(); } } void PartSashContainer::SetVisible(bool makeVisible) { if (makeVisible == this->GetVisible()) { return; } //if (!SwtUtil.isDisposed(this.parent)) //{ Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(this->parent, makeVisible); //} LayoutPart::SetVisible(makeVisible); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->SetVisible(makeVisible); // && (zoomedPart == null || child == zoomedPart)); } } LayoutPart::Pointer PartSashContainer::FindBottomRight() { if (root == 0) { return LayoutPart::Pointer(0); } return root->FindBottomRight(); } -Rectangle PartSashContainer::GetBounds() +QRect PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() const { return children; } void* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } void* PartSashContainer::GetParent() { return parent; } bool PartSashContainer::IsChild(LayoutPart::Pointer part) { return std::find(children.begin(), children.end(), part) != children.end(); } void PartSashContainer::ResizeChild(LayoutPart::Pointer childThatChanged) { if (root != 0) { LayoutTree::Pointer tree = root->Find(childThatChanged); if (tree != 0) { tree->FlushCache(); } } this->FlushLayout(); } void PartSashContainer::Remove(LayoutPart::Pointer child) { // if (child == getZoomedPart()) // { // childRequestZoomOut(); // } if (!this->IsChild(child)) { return; } children.removeAll(child); if (root != 0) { root = root->Remove(child); } this->ChildRemoved(child); if (active) { child->SetVisible(false); child->SetContainer(ILayoutContainer::Pointer(0)); this->FlushLayout(); } } void PartSashContainer::FlushLayout() { layoutDirty = true; LayoutPart::FlushLayout(); if (layoutDirty) { this->ResizeSashes(); } } void PartSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // if (oldChild == getZoomedPart()) // { // if (newChild.Cast ().IsNotNull()) // { // childRequestZoomOut(); // } // else // { // zoomedPart.setZoomed(false); // zoomedPart = newChild; // zoomedPart.setZoomed(true); // } // } children.erase(std::find(children.begin(), children.end(), oldChild)); children.push_back(newChild); this->ChildAdded(newChild); if (root != 0) { LayoutTree::Pointer leaf; leaf = root->Find(oldChild); if (leaf != 0) { leaf->SetPart(newChild); } } this->ChildRemoved(oldChild); if (active) { oldChild->SetVisible(false); oldChild->SetContainer(ILayoutContainer::Pointer(0)); newChild->CreateControl(parent); newChild->SetContainer(ILayoutContainer::Pointer(this)); newChild->SetVisible(true); //zoomedPart == null || zoomedPart == newChild); this->ResizeChild(newChild); } } void PartSashContainer::ResizeSashes() { layoutDirty = false; if (!active) { return; } // if (isZoomed()) // { // getZoomedPart().setBounds(parent.getClientArea()); // } // else { if (root != 0) { root->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea( parent)); } } } int PartSashContainer::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { // if (isZoomed()) // { // return getZoomedPart().computePreferredSize(width, availableParallel, // availablePerpendicular, preferredParallel); // } if (root != 0) { return root->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } return preferredParallel; } int PartSashContainer::GetSizeFlags(bool width) { // if (isZoomed()) // { // return getZoomedPart().getSizeFlags(width); // } if (root != 0) { return root->GetSizeFlags(width); } return 0; } -void PartSashContainer::SetBounds(const Rectangle& r) +void PartSashContainer::SetBounds(const QRect& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } IDropTarget::Pointer PartSashContainer::Drag(void* /*currentControl*/, - const Object::Pointer& draggedObject, const Point& position, - const Rectangle& /*dragRectangle*/) + const Object::Pointer& draggedObject, const QPoint& position, + const QRect& /*dragRectangle*/) { if (!(draggedObject.Cast () != 0 || draggedObject.Cast () != 0)) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); PartStack::Pointer sourceContainer = draggedObject.Cast (); if (sourceContainer == 0) { sourceContainer = sourcePart->GetStack(); } if (!this->IsStackType(sourceContainer) && !this->IsPaneType(sourcePart)) { return IDropTarget::Pointer(0); } IWorkbenchWindow::Pointer window = sourcePart ? sourcePart->GetWorkbenchWindow() : sourceContainer->GetWorkbenchWindow(); bool differentWindows = window != this->GetWorkbenchWindow(); bool editorDropOK = ((sourceContainer->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) && window->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } - Rectangle containerBounds = DragUtil::GetDisplayBounds(parent); + QRect containerBounds = DragUtil::GetDisplayBounds(parent); LayoutPart::Pointer targetPart; // If this container has no visible children if (this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) == 0) { return this->CreateDropTarget(draggedObject, Constants::CENTER, Constants::CENTER, Object::Pointer(0)); } - if (containerBounds.Contains(position)) + if (containerBounds.contains(position)) { if (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { void* targetControl = targetPart->GetControl(); - Rectangle targetBounds = DragUtil::GetDisplayBounds(targetControl); + QRect targetBounds = DragUtil::GetDisplayBounds(targetControl); int side = Geometry::GetClosestSide(targetBounds, position); int distance = Geometry::GetDistanceFromEdge(targetBounds, position, side); // is the source coming from a standalone part bool standalone = (this->IsStackType(sourceContainer) && sourceContainer->IsStandalone()) || (this->IsPaneType(sourcePart) && sourcePart->GetStack()->IsStandalone()); // Only allow dropping onto an existing stack from different windows if (differentWindows && targetPart.Cast () != 0 && targetPart.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) { IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); return target; } // Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor if (distance >= 5 && !standalone) { // Otherwise, ask the part if it has any special meaning for this drop location IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); if (target != 0) { return target; } } if (distance > 30 && this->IsStackType(targetPart.Cast ()) && !standalone) { PartStack::Pointer targetContainer = targetPart.Cast (); if (targetContainer->AllowsAdd(sourcePart)) { side = Constants::CENTER; } } // If the part doesn't want to override this drop location then drop on the edge // A "pointless drop" would be one that will put the dragged object back where it started. // Note that it should be perfectly valid to drag an object back to where it came from -- however, // the drop should be ignored. bool pointlessDrop = false; // = isZoomed(); if (!sourcePart && sourceContainer == targetPart) { pointlessDrop = true; } if ((sourceContainer != 0) && (sourceContainer == targetPart) && this->GetVisibleChildrenCount(sourceContainer.Cast()) <= 1) { pointlessDrop = true; } if (side == Constants::CENTER && sourceContainer == targetPart) { pointlessDrop = true; } int cursor = side; if (pointlessDrop) { side = Constants::NONE; cursor = Constants::CENTER; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, targetPart); else return this->CreateDropTarget(sourceContainer, side, cursor, targetPart); } } else { // We only allow dropping into a stack, not creating one if (differentWindows) return IDropTarget::Pointer(0); int side = Geometry::GetClosestSide(containerBounds, position); bool pointlessDrop = false; // = isZoomed(); if (/*(this->IsStackType(sourceContainer) && sourceContainer == this) ||*/ (this->IsPaneType(sourcePart) && this->GetVisibleChildrenCount( sourceContainer.Cast()) <= 1) && sourceContainer->GetContainer() == this) { if (root == 0 || this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) <= 1) { pointlessDrop = true; } } int cursor = Geometry::GetOppositeSide(side); if (pointlessDrop) { side = Constants::NONE; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, Object::Pointer(0)); else return this->CreateDropTarget(sourceContainer, side, cursor, Object::Pointer(0)); } return IDropTarget::Pointer(0); } PartSashContainer::SashContainerDropTarget::Pointer PartSashContainer::CreateDropTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { if (dropTarget == 0) { dropTarget = new SashContainerDropTarget(this, sourcePart, side, cursor, targetPart); } else { dropTarget->SetTarget(sourcePart, side, cursor, targetPart); } return dropTarget; } void PartSashContainer::Stack(LayoutPart::Pointer newPart, ILayoutContainer::Pointer container) { //this->GetControl().setRedraw(false); // Only deref the part if it is being referenced in -this- perspective Perspective::Pointer persp = page->GetActivePerspective(); PerspectiveHelper* pres = (persp != 0) ? persp->GetPresentation() : 0; if (pres != 0 && container.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { IWorkbenchPartReference::Pointer newPartRef = newPart.Cast ()->GetPartReference(); IViewReference::Pointer vRef = newPartRef.Cast (); if (vRef != 0) { LayoutPart::Pointer fpp = pres->FindPart(vRef->GetId(), vRef->GetSecondaryId()); if (fpp != 0) { // Remove the part from old container. this->DerefPart(newPart); } } } else { // Remove the part from old container. this->DerefPart(newPart); } // Reparent part and add it to the workbook newPart->Reparent(this->GetParent()); container->Add(newPart); //getControl().setRedraw(true); } void PartSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { ILayoutContainer::Pointer container = sourcePart->GetContainer(); if (container != 0) { container->Remove(sourcePart); if (this->IsStackType(container) && container.Cast () != 0) { if (container->GetChildren().size() == 0) { LayoutPart::Pointer stack = container.Cast (); this->Remove(stack); stack->Dispose(); } } } } std::size_t PartSashContainer::GetVisibleChildrenCount( ILayoutContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } ILayoutContainer::ChildrenType children = container->GetChildren(); std::size_t count = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { count++; } } return count; } float PartSashContainer::GetDockingRatio(Object::Pointer /*dragged*/, ILayoutContainer::Pointer /*target*/) { return 0.5f; } void PartSashContainer::DescribeLayout(QString& buf) const { if (root == 0) { return; } // if (isZoomed()) // { // buf.append("zoomed "); //$NON-NLS-1$ // root.describeLayout(buf); // } // else { buf.append("layout "); //$NON-NLS-1$ root->DescribeLayout(buf); } } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative) { if (child == 0) { return; } if (relative != 0 && !this->IsChild(relative)) { return; } if (relationship < IPageLayout::LEFT || relationship > IPageLayout::BOTTOM) { relationship = IPageLayout::LEFT; } // store info about relative positions RelationshipInfo info; info.part = child; info.relationship = relationship; info.left = left; info.right = right; info.relative = relative; this->AddChild(info); } bool PartSashContainer::AllowsAutoFocus() { return true; } void PartSashContainer::StartDeferringEvents() { LayoutPart::StartDeferringEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(true); } } void PartSashContainer::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(false); } } void PartSashContainer::TestInvariants() { LayoutPart::TestInvariants(); // If we have a parent container, ensure that we are displaying the zoomed appearance iff // our parent is zoomed in on us // if (this->GetContainer() != 0) // { // Assert.isTrue((getZoomedPart() != null) == (getContainer().childIsZoomed( // this))); // } ILayoutContainer::ChildrenType childArray = this->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = childArray.begin(); iter != childArray.end(); ++iter) { (*iter)->TestInvariants(); } // If we're zoomed, ensure that we're actually zoomed into one of our children // if (isZoomed()) // { // Assert.isTrue(children.contains(zoomedPart)); // } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h index 54bf71059c..87c9eefc04 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h @@ -1,702 +1,699 @@ /*=================================================================== 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 BERRYPARTSASHCONTAINER_H_ #define BERRYPARTSASHCONTAINER_H_ #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryILayoutContainer.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" -#include "tweaklets/berryDnDTweaklet.h" -#include "berryRectangle.h" - #include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartPane; class LayoutTree; class PartStack; /** * \ingroup org_blueberry_ui_internal * * Abstract container that groups various layout * parts (possibly other containers) together as * a unit. Manages the placement and size of these * layout parts based on the location of sashes within * the container. * * GUI specializations must override the following methods * (read their documentation for implementation details): * *
    *
  • PartSashContainer */ class PartSashContainer: public LayoutPart, public ILayoutContainer, public IDragOverListener { public: berryObjectMacro(PartSashContainer) friend class LayoutTree; friend class LayoutTreeNode; friend class PageLayout; private: void* parentWidget; //LayoutPart::Pointer zoomedPart; /* Indicates if the children of a sash container should be aligned from left to right * or the other way around. This is important if one child does * not occupy all of the available space. Then the empty space * is either on the left, or on the right side. */ bool static leftToRight; protected: struct ControlListener : public GuiTk::IControlListener { ControlListener(PartSashContainer* partSashContainer); Events::Types GetEventTypes() const; void ControlResized(GuiTk::ControlEvent::Pointer e); private: PartSashContainer* partSashContainer; }; void* parent; GuiTk::IControlListener::Pointer resizeListener; SmartPointer root; WorkbenchPage* page; bool active; bool layoutDirty; /* Array of LayoutPart */ ILayoutContainer::ChildrenType children; protected: struct RelationshipInfo { LayoutPart::Pointer part; LayoutPart::Pointer relative; int relationship; /** * Preferred size for the left child (this would be the size, in pixels of the child * at the time the sash was last moved) */ int left; /** * Preferred size for the right child (this would be the size, in pixels of the child * at the time the sash was last moved) */ int right; }; private: class SashContainerDropTarget : public AbstractDropTarget { private: int side; int cursor; // This is a ILayoutPart or ILayoutContainer Object::Pointer targetPart; // This is a ILayoutPart or ILayoutContainer Object::Pointer sourcePart; PartSashContainer* partSashContainer; public: berryObjectMacro(SashContainerDropTarget) SashContainerDropTarget(PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); void SetTarget(Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); void Drop(); - DnDTweaklet::CursorType GetCursor(); + CursorType GetCursor(); - Rectangle GetSnapRectangle(); + QRect GetSnapRectangle(); }; SashContainerDropTarget::Pointer dropTarget; public: /** * Constructs a PartSashContainer with the given id under the given page * and parentWidget. * * GUI specializations must hook */ PartSashContainer(const QString& id, WorkbenchPage* page, void* parentWidget); ~PartSashContainer(); /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#obscuredByZoom(org.blueberry.ui.internal.LayoutPart) */ // public: bool childObscuredByZoom(LayoutPart toTest) { // LayoutPart zoomPart = getZoomedPart(); // // if (zoomPart != null && toTest != zoomPart) { // return true; // } // return isObscuredByZoom(); // } /** * Given an object associated with a drag (a PartPane or PartStack), this returns * the actual PartPanes being dragged. * * @param pane * @return */ private: QList > GetVisibleParts(Object::Pointer pane); /** * Find the sashs around the specified part. */ public: void FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes); public: /** * Add a part. */ virtual void Add(LayoutPart::Pointer child); virtual void AddPart(LayoutPart::Pointer child); /** * Add a part relative to another. For compatibility only. New code should use * addEnhanced, above. * * @param child the new part to add * @param relationship one of PageLayout.TOP, PageLayout.BOTTOM, PageLayout.LEFT, or PageLayout.RIGHT * @param ratio a value between 0.0 and 1.0, indicating how much space will be allocated to the UPPER-LEFT pane * @param relative part where the new part will be attached */ virtual void Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative); protected: virtual void DropObject(const QList& toDrop, LayoutPart::Pointer visiblePart, Object::Pointer targetPart, int side); /** * Add a new part relative to another. This should be used in place of add. * It differs as follows: *
      *
    • relationships are specified using SWT direction constants
    • *
    • the ratio applies to the newly added child -- not the upper-left child
    • *
    * * @param child new part to add to the layout * @param swtDirectionConstant one of SWT.TOP, SWT.BOTTOM, SWT.LEFT, or SWT.RIGHT * @param ratioForNewPart a value between 0.0 and 1.0 specifying how much space will be allocated for the newly added part * @param relative existing part indicating where the new child should be attached * @since 3.0 */ protected: virtual void AddEnhanced(LayoutPart::Pointer child, int swtDirectionConstant, float ratioForNewPart, LayoutPart::Pointer relative); protected: - static int MeasureTree(const Rectangle& outerBounds, + static int MeasureTree(const QRect& outerBounds, SmartPointer toMeasure, bool horizontal); protected: virtual void AddChild(const RelationshipInfo& info); /** * Adds the child using ratio and position attributes * from the specified placeholder without replacing * the placeholder * * FIXME: I believe there is a bug in computeRelation() * when a part is positioned relative to the editorarea. * We end up with a null relative and 0.0 for a ratio. */ public: virtual void AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder); /** * See ILayoutContainer#allowBorder */ public: virtual bool AllowsBorder(); /** * Notification that a child layout part has been * added to the container. Subclasses may override * this method to perform any container specific * work. */ protected: virtual void ChildAdded(LayoutPart::Pointer child); /** * Notification that a child layout part has been * removed from the container. Subclasses may override * this method to perform any container specific * work. */ protected: virtual void ChildRemoved(LayoutPart::Pointer child); /** * Returns an array with all the relation ship between the * parts. */ public: virtual QList ComputeRelation(); public: virtual void SetActive(bool isActive); /** * @see LayoutPart#getControl */ public: void CreateControl(void* parentWidget); /** * Subclasses override this method to specify * the composite to use to parent all children * layout parts it contains. */ protected: virtual void* CreateParent(void* parentWidget) = 0; /** * @see LayoutPart#dispose */ public: virtual void Dispose(); /** * Subclasses override this method to dispose * of any swt resources created during createParent. */ protected: virtual void DisposeParent() = 0; /** * Dispose all sashs used in this perspective. */ public: virtual void DisposeSashes(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setVisible(boolean) */ public: void SetVisible(bool makeVisible); /** * Return the most bottom right part or null if none. */ public: virtual LayoutPart::Pointer FindBottomRight(); /** * @see LayoutPart#getBounds */ public: - Rectangle GetBounds(); + QRect GetBounds(); /** * @see ILayoutContainer#getChildren */ public: ChildrenType GetChildren() const; /** * @see LayoutPart#getControl */ public: void* GetControl(); public: virtual SmartPointer GetLayoutTree(); /** * For themes. * * @return the current WorkbenchPage. */ public: virtual SmartPointer GetPage(); /** * Returns the composite used to parent all the * layout parts contained within. */ public: virtual void* GetParent(); protected: virtual bool IsChild(LayoutPart::Pointer part); /** * Returns whether this container is zoomed. */ // public: bool IsZoomed() { // return (zoomedPart != null); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#forceLayout(org.blueberry.ui.internal.LayoutPart) */ public: void ResizeChild(LayoutPart::Pointer childThatChanged); /** * Remove a part. */ public: void Remove(LayoutPart::Pointer child); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#forceLayout() */ public: void FlushLayout(); /** * Replace one part with another. */ public: void Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild); private: void ResizeSashes(); /** * Returns the maximum size that can be utilized by this part if the given width and * height are available. Parts can overload this if they have a quantized set of preferred * sizes. * * @param width available horizontal space (pixels) * @return returns a new point where point.x is <= availableWidth and point.y is <= availableHeight */ public: virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: int GetSizeFlags(bool width); /** * @see LayoutPart#setBounds */ public: - void SetBounds(const Rectangle& r); + void SetBounds(const QRect& r); /** * Zoom in on a particular layout part. * * The implementation of zoom is quite simple. When zoom occurs we create * a zoom root which only contains the zoom part. We store the old * root in unzoomRoot and then active the zoom root. When unzoom occurs * we restore the unzoomRoot and dispose the zoom root. * * Note: Method assumes we are active. */ // private: void zoomIn(LayoutPart part) { // // Sanity check. // if (isZoomed()) { // return; // } // // // Hide the sashes // root.disposeSashes(); // // // Make all parts invisible except for the zoomed part // LayoutPart[] children = getChildren(); // for (int i = 0; i < children.length; i++) { // LayoutPart child = children[i]; // child.setVisible(child == part); // } // // zoomedPart = part; // // // Notify the part that it has been zoomed // part.setZoomed(true); // // // Remember that we need to trigger a layout // layoutDirty = true; // } /** * Returns the currently zoomed part or null if none * * @return the currently zoomed part or null if none * @since 3.1 */ // public: LayoutPart getZoomedPart() { // return zoomedPart; // } // public: void childRequestZoomIn(LayoutPart toZoom) { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(false); // } // try { // zoomIn(toZoom); // // requestZoomIn(); // // if (layoutDirty) { // resizeSashes(); // } // } finally { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(true); // } // } // } // public: void childRequestZoomOut() { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(false); // } // try { // zoomOut(); // // requestZoomOut(); // // if (layoutDirty) { // resizeSashes(); // } // } finally { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(true); // } // } // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setZoomed(boolean) */ // public: void setZoomed(boolean isZoomed) { // if (!isZoomed) { // zoomOut(); // } else { // if (!isZoomed()) { // LayoutPart toZoom = pickPartToZoom(); // // if (toZoom != null) { // zoomIn(toZoom); // } // } // } // super.setZoomed(isZoomed); // } // public: LayoutPart pickPartToZoom() { // return findBottomRight(); // } /** * Zoom out. * * See zoomIn for implementation details. * * Note: Method assumes we are active. */ // private: void zoomOut() { // // Sanity check. // if (!isZoomed()) { // return; // } // // LayoutPart zoomedPart = this.zoomedPart; // this.zoomedPart = null; // // Inform the part that it is no longer zoomed // zoomedPart.setZoomed(false); // // // Make all children visible // LayoutPart[] children = getChildren(); // for (int i = 0; i < children.length; i++) { // LayoutPart child = children[i]; // // child.setVisible(true); // } // // // Recreate the sashes // root.createControl(getParent()); // // // Ensure that the part being un-zoomed will have its size refreshed. // LayoutTree node = root.find(zoomedPart); // node.flushCache(); // // layoutDirty = true; // } /* (non-Javadoc) - * @see org.blueberry.ui.internal.dnd.IDragOverListener#drag(org.blueberry.swt.widgets.Control, java.lang.Object, org.blueberry.swt.graphics.Point, org.blueberry.swt.graphics.Rectangle) + * @see org.blueberry.ui.internal.dnd.IDragOverListener#drag(org.blueberry.swt.widgets.Control, java.lang.Object, org.blueberry.swt.graphics.QPoint, org.blueberry.swt.graphics.QRect) */ public: IDropTarget::Pointer Drag(void* currentControl, const Object::Pointer& draggedObject, - const Point& position, const Rectangle& dragRectangle); + const QPoint& position, const QRect& dragRectangle); /** * @param sourcePart * @param targetPart * @param side * @param cursor * @return * @since 3.1 */ private: SashContainerDropTarget::Pointer CreateDropTarget(Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); /** * Returns true iff this PartSashContainer allows its parts to be stacked onto the given * container. * * @param container * @return */ public: virtual bool IsStackType(ILayoutContainer::Pointer toTest) = 0; public: virtual bool IsPaneType(LayoutPart::Pointer toTest) = 0; protected: virtual SmartPointer CreateStack() = 0; public: virtual void Stack(LayoutPart::Pointer newPart, SmartPointer container); /** * @param container * @param visiblePart */ protected: virtual void SetVisiblePart(ILayoutContainer::Pointer container, SmartPointer visiblePart) = 0; /** * @param container * @return */ protected: virtual LayoutPart::Pointer GetVisiblePart( ILayoutContainer::Pointer container) = 0; /** * @param sourcePart */ protected: virtual void DerefPart(LayoutPart::Pointer sourcePart); protected: virtual std::size_t GetVisibleChildrenCount(ILayoutContainer::Pointer container); protected: virtual float GetDockingRatio(Object::Pointer dragged, ILayoutContainer::Pointer target); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. * * @param buf */ public: void DescribeLayout(QString& buf) const; /** * Adds a new child to the container relative to some part * * @param child * @param relationship * @param left preferred pixel size of the left/top child * @param right preferred pixel size of the right/bottom child * @param relative relative part */ protected: virtual void Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative); /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#isZoomed(org.blueberry.ui.internal.LayoutPart) */ // public: bool childIsZoomed(LayoutPart toTest) { // return toTest == getZoomedPart(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#allowsAutoFocus() */ public: bool AllowsAutoFocus(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#startDeferringEvents() */ protected: void StartDeferringEvents(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#handleDeferredEvents() */ protected: void HandleDeferredEvents(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#testInvariants() */ public: void TestInvariants(); }; } #endif /*BERRYPARTSASHCONTAINER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.cpp index 3023ea10f2..1d1c1e5680 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.cpp @@ -1,1609 +1,1609 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryPartStack.h" #include "berryPerspective.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchPlugin.h" #include "berryPresentationSerializer.h" #include "berryDragUtil.h" #include "berryEditorAreaHelper.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchConstants.h" #include "berryXMLMemento.h" #include "berryIWorkbenchPartConstants.h" #include "berryGeometry.h" #include namespace berry { const int PartStack::PROP_SELECTION = 0x42; PartStack::PartStackDropResult::Pointer PartStack::dropResult( new PartStack::PartStackDropResult()); void PartStack::PartStackDropResult::SetTarget(PartStack::Pointer stack, PartPane::Pointer pane, StackDropResult::Pointer result) { this->pane = pane; this->dropResult = result; this->stack = stack; } void PartStack::PartStackDropResult::Drop() { // If we're dragging a pane over itself do nothing //if (dropResult.getInsertionPoint() == pane.getPresentablePart()) { return; }; Object::Pointer cookie; if (dropResult != 0) { cookie = dropResult->GetCookie(); } PartPane::Pointer pane(this->pane); PartStack::Pointer stack(this->stack); // Handle cross window drops by opening a new editor if (pane->GetPartReference().Cast () != 0) { IEditorReference::Pointer editorRef = pane->GetPartReference().Cast< IEditorReference> (); if (pane->GetWorkbenchWindow() != stack->GetWorkbenchWindow()) { try { IEditorInput::Pointer input = editorRef->GetEditorInput(); // Close the old editor and capture the actual closed state incase of a 'cancel' bool editorClosed = pane->GetPage()->CloseEditor(editorRef, true); // Only open open the new editor if the old one closed if (editorClosed) stack->GetPage()->OpenEditor(input, editorRef->GetId()); return; } catch (const PartInitException& e) { //e.printStackTrace(); BERRY_ERROR << e.what(); } } } if (pane->GetContainer() != stack) { // Moving from another stack stack->DerefPart(pane); pane->Reparent(stack->GetParent()); stack->Add(pane, cookie); stack->SetSelection(pane); pane->SetFocus(); } else if (cookie != 0) { // Rearranging within this stack stack->GetPresentation()->MovePart(stack->GetPresentablePart(pane), cookie); } } -DnDTweaklet::CursorType PartStack::PartStackDropResult::GetCursor() +CursorType PartStack::PartStackDropResult::GetCursor() { - return DnDTweaklet::CURSOR_CENTER; + return CURSOR_CENTER; } -Rectangle PartStack::PartStackDropResult::GetSnapRectangle() +QRect PartStack::PartStackDropResult::GetSnapRectangle() { if (dropResult == 0) { return DragUtil::GetDisplayBounds(stack.Lock()->GetControl()); } return dropResult->GetSnapRectangle(); } PartStack::MyStackPresentationSite::MyStackPresentationSite(PartStack* stack) : partStack(stack) { } void PartStack::MyStackPresentationSite::Close(IPresentablePart::Pointer part) { partStack->Close(part); } void PartStack::MyStackPresentationSite::Close(const QList< IPresentablePart::Pointer>& parts) { partStack->Close(parts); } void PartStack::MyStackPresentationSite::DragStart( - IPresentablePart::Pointer beingDragged, Point& initialLocation, + IPresentablePart::Pointer beingDragged, QPoint& initialLocation, bool keyboard) { partStack->DragStart(beingDragged, initialLocation, keyboard); } -void PartStack::MyStackPresentationSite::DragStart(Point& initialLocation, +void PartStack::MyStackPresentationSite::DragStart(QPoint& initialLocation, bool keyboard) { partStack->DragStart(IPresentablePart::Pointer(0), initialLocation, keyboard); } bool PartStack::MyStackPresentationSite::IsPartMoveable( IPresentablePart::Pointer part) { return partStack->IsMoveable(part); } void PartStack::MyStackPresentationSite::SelectPart( IPresentablePart::Pointer toSelect) { partStack->PresentationSelectionChanged(toSelect); } bool PartStack::MyStackPresentationSite::SupportsState(int state) { return partStack->SupportsState(state); } void PartStack::MyStackPresentationSite::SetState(int newState) { partStack->SetState(newState); } IPresentablePart::Pointer PartStack::MyStackPresentationSite::GetSelectedPart() { return partStack->GetSelectedPart(); } // void AddSystemActions(IMenuManager menuManager) { // PartStack.this.addSystemActions(menuManager); // } bool PartStack::MyStackPresentationSite::IsStackMoveable() { return partStack->CanMoveFolder(); } void PartStack::MyStackPresentationSite::FlushLayout() { partStack->FlushLayout(); } PartStack::PresentableVector PartStack::MyStackPresentationSite::GetPartList() { return partStack->GetPresentableParts(); } QString PartStack::MyStackPresentationSite::GetProperty( const QString& id) { return partStack->GetProperty(id); } PartStack::PartStack(WorkbenchPage* p, bool allowsStateChanges, int appear, IPresentationFactory* fac) : LayoutPart("PartStack"), page(p), isActive(true), allowStateChanges( allowsStateChanges), appearance(appear), ignoreSelectionChanges(false), factory(fac) { QString str; QTextStream buf(&str); buf << "PartStack@" << this; this->SetID(str); presentationSite = new MyStackPresentationSite(this); } bool PartStack::IsMoveable(IPresentablePart::Pointer part) { PartPane::Pointer pane = this->GetPaneFor(part); Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } IWorkbenchPartReference::Pointer partRef = pane->GetPartReference(); if (partRef.Cast () != 0) return perspective->IsMoveable(partRef.Cast ()); return true; } bool PartStack::SupportsState(int /*newState*/) { if (page->IsFixedLayout()) { return false; } return allowStateChanges; } bool PartStack::CanMoveFolder() { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) return true; Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return false; } // We need to search if one of the presentations is not moveable // if that's the case the whole folder should not be moveable IStackPresentationSite::Pointer presenationSite; if ((presenationSite = this->GetPresentationSite()) != 0) { QList parts = presenationSite->GetPartList(); for (QList::iterator iter = parts.begin(); iter != parts.end(); ++iter) { if (!presenationSite->IsPartMoveable(*iter)) { return false; } } } return !perspective->IsFixedLayout(); } void PartStack::DerefPart(LayoutPart::Pointer toDeref) { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) EditorAreaHelper::DerefPart(toDeref); else this->GetPage()->GetActivePerspective()->GetPresentation()->DerefPart( toDeref); } bool PartStack::AllowsDrop(PartPane::Pointer part) { PartStack::Pointer stack = part->GetContainer().Cast (); if (stack != 0) { if (stack->appearance == this->appearance) return true; } return false; } void PartStack::AddListener(IPropertyChangeListener *listener) { propEvents.AddListener(listener); } void PartStack::RemoveListener(IPropertyChangeListener *listener) { propEvents.RemoveListener(listener); } int PartStack::GetAppearance() const { return appearance; } QString PartStack::GetID() const { return LayoutPart::GetID(); } bool PartStack::IsStandalone() { return (appearance == PresentationFactoryUtil::ROLE_STANDALONE || appearance == PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE); } IPresentablePart::Pointer PartStack::GetSelectedPart() { return presentationCurrent.Cast (); } IStackPresentationSite::Pointer PartStack::GetPresentationSite() { return presentationSite; } void PartStack::TestInvariants() { void* focusControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetFocusControl(); bool currentFound = false; ChildVector children = this->GetChildren(); for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; // No 0 children allowed poco_assert(child != 0) ; // "0 children are not allowed in PartStack" // Ensure that all the PartPanes have an associated presentable part IPresentablePart::Pointer part = this->GetPresentablePart(child); if (!child->IsPlaceHolder()) { poco_assert(part != 0); // "All PartPanes must have a non-0 IPresentablePart" } // Ensure that the child's backpointer points to this stack ILayoutContainer::Pointer childContainer = child->GetContainer(); // Disable tests for placeholders -- PartPlaceholder backpointers don't // obey the usual rules -- they sometimes point to a container placeholder // for this stack instead of the real stack. if (!child->IsPlaceHolder()) { // If the widgetry exists, the child's backpointer must point to us poco_assert(childContainer.GetPointer() == this); // "PartStack has a child that thinks it has a different parent" // If this child has focus, then ensure that it is selected and that we have // the active appearance. if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(child->GetControl(), focusControl)) { poco_assert(child == current); // "The part with focus is not the selected part" // focus check commented out since it fails when focus workaround in LayoutPart.setVisible is not present // Assert.isTrue(getActive() == StackPresentation.AS_ACTIVE_FOCUS); } } // Ensure that "current" points to a valid child if (child == current) { currentFound = true; } // Test the child's internal state child->TestInvariants(); } // If we have at least one child, ensure that the "current" pointer points to one of them if (this->GetPresentableParts().size()> 0) { poco_assert(currentFound); StackPresentation::Pointer presentation = this->GetPresentation(); // If the presentation controls have focus, ensure that we have the active appearance if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(presentation->GetControl(), focusControl)) { poco_assert(this->GetActive() == StackPresentation::AS_ACTIVE_FOCUS); // "The presentation has focus but does not have the active appearance" } } // Check to that we're displaying the zoomed icon iff we're actually maximized //poco_assert((this->GetState() == IStackPresentationSite::STATE_MAXIMIZED) // == (this->GetContainer() != 0 && this->GetContainer()->ChildIsZoomed(this))); } void PartStack::DescribeLayout(QString& buf) const { int activeState = this->GetActive(); if (activeState == StackPresentation::AS_ACTIVE_FOCUS) { buf.append("active "); //$NON-NLS-1$ } else if (activeState == StackPresentation::AS_ACTIVE_NOFOCUS) { buf.append("active_nofocus "); //$NON-NLS-1$ } buf.append("("); //$NON-NLS-1$ ChildVector children = this->GetChildren(); int visibleChildren = 0; for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer next = *iter; if (!next->IsPlaceHolder()) { if (iter != children.begin()) { buf.append(", "); //$NON-NLS-1$ } if (next == requestedCurrent) { buf.append("*"); //$NON-NLS-1$ } next->DescribeLayout(buf); visibleChildren++; } } buf.append(")"); //$NON-NLS-1$ } void PartStack::Add(LayoutPart::Pointer child) { this->Add(child, Object::Pointer(0)); } void PartStack::Add(LayoutPart::Pointer newChild, Object::Pointer cookie) { children.push_back(newChild); // Fix for bug 78470: if(newChild->GetContainer().Cast() == 0) { newChild->SetContainer(ILayoutContainer::Pointer(this)); } this->ShowPart(newChild, cookie); } bool PartStack::AllowsAdd(LayoutPart::Pointer /*toAdd*/) { return !this->IsStandalone(); } bool PartStack::AllowsAutoFocus() { if (presentationSite->GetState() == IStackPresentationSite::STATE_MINIMIZED) { return false; } return LayoutPart::AllowsAutoFocus(); } void PartStack::Close(const QList& parts) { for (int idx = 0; idx < parts.size(); idx++) { IPresentablePart::Pointer part = parts[idx]; this->Close(part); } } void PartStack::Close(IPresentablePart::Pointer part) { if (!presentationSite->IsCloseable(part)) { return; } PartPane::Pointer pane = this->GetPaneFor(part); if (pane != 0) { pane->DoHide(); } } IPresentationFactory* PartStack::GetFactory() { if (factory != 0) { return factory; } return WorkbenchPlugin::GetDefault()->GetPresentationFactory(); } void PartStack::CreateControl(void* parent) { if (this->GetPresentation() != 0) { return; } IPresentationFactory* factory = this->GetFactory(); PresentableVector partList = this->GetPresentableParts(); PresentationSerializer serializer(partList); StackPresentation::Pointer presentation = PresentationFactoryUtil ::CreatePresentation(factory, appearance, parent, presentationSite, &serializer, savedPresentationState); this->CreateControl(parent, presentation); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveBelow(this->GetControl(), 0); } -IDropTarget::Pointer PartStack::GetDropTarget(Object::Pointer draggedObject, const Point& position) +IDropTarget::Pointer PartStack::GetDropTarget(Object::Pointer draggedObject, const QPoint& position) { if (draggedObject.Cast() == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer pane = draggedObject.Cast(); if (this->IsStandalone() || !this->AllowsDrop(pane)) { return IDropTarget::Pointer(0); } // Don't allow views to be dragged between windows bool differentWindows = pane->GetWorkbenchWindow() != this->GetWorkbenchWindow(); bool editorDropOK = ((pane->GetPartReference().Cast() != 0) && pane->GetWorkbenchWindow()->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } StackDropResult::Pointer dropResult = this->GetPresentation()->DragOver( this->GetControl(), position); if (dropResult == 0) { return IDropTarget::Pointer(0); } return this->CreateDropTarget(pane, dropResult); } -void PartStack::SetBounds(const Rectangle& r) +void PartStack::SetBounds(const QRect& r) { if (this->GetPresentation() != 0) { this->GetPresentation()->SetBounds(r); } } IDropTarget::Pointer PartStack::CreateDropTarget(PartPane::Pointer pane, StackDropResult::Pointer result) { dropResult->SetTarget(PartStack::Pointer(this), pane, result); return dropResult; } void PartStack::SetActive(bool isActive) { this->isActive = isActive; // Add all visible children to the presentation for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->SetContainer(isActive ? ILayoutContainer::Pointer(this) : ILayoutContainer::Pointer(0)); } for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } void PartStack::CreateControl(void* /*parent*/, StackPresentation::Pointer presentation) { poco_assert(this->GetPresentation() == 0); if (presentationSite->GetPresentation() != 0) { return; } presentationSite->SetPresentation(presentation); // Add all visible children to the presentation // Use a copy of the current set of children to avoid a ConcurrentModificationException // if a part is added to the same stack while iterating over the children (bug 78470) ChildVector childParts(children); for (ChildVector::iterator iter = childParts.begin(); iter != childParts.end(); ++iter) { this->ShowPart(*iter, Object::Pointer(0)); } if (savedPresentationState != 0) { PresentableVector partList = this->GetPresentableParts(); PresentationSerializer serializer(partList); presentation->RestoreState(&serializer, savedPresentationState); } //void* ctrl = this->GetPresentation()->GetControl(); //TODO control setData ? //ctrl.setData(this); // We should not have a placeholder selected once we've created the widgetry if (requestedCurrent != 0 && requestedCurrent->IsPlaceHolder()) { requestedCurrent = 0; this->UpdateContainerVisibleTab(); } this->RefreshPresentationSelection(); } void PartStack::SavePresentationState() { if (this->GetPresentation() == 0) { return; } {// Save the presentation's state before disposing it XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_PRESENTATION); memento->PutString(WorkbenchConstants::TAG_ID, this->GetFactory()->GetId()); QList parts(this->GetPresentableParts()); PresentationSerializer serializer(parts); this->GetPresentation()->SaveState(&serializer, memento); // Store the memento in savedPresentationState savedPresentationState = memento; } } PartStack::~PartStack() { //BERRY_INFO << "DELETING PARTSTACK"; } void PartStack::Dispose() { if (this->GetPresentation() == 0) { return; } this->SavePresentationState(); // for (PresentableVector::iterator iter = presentableParts.begin(); // iter != presentableParts.end(); ++iter) // { // iter->Cast()->Dispose(); // } presentableParts.clear(); presentationCurrent = 0; current = 0; this->FireInternalPropertyChange(PROP_SELECTION); } void PartStack::FindSashes(LayoutPart::Pointer /*toFind*/, PartPane::Sashes& sashes) { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } -Rectangle PartStack::GetBounds() +QRect PartStack::GetBounds() { if (this->GetPresentation() == 0) { - return Rectangle(0, 0, 0, 0); + return QRect(0, 0, 0, 0); } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl()); } QList PartStack::GetChildren() const { return children; } void* PartStack::GetControl() { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation == 0) { return 0; } return presentation->GetControl(); } /** * Answer the number of children. */ PartStack::ChildVector::size_type PartStack::GetItemCount() { if (this->GetPresentation() == 0) { return children.size(); } return this->GetPresentableParts().size(); } PartPane::Pointer PartStack::GetPaneFor(IPresentablePart::Pointer part) { if (part == 0 || part.Cast() == 0) { return PartPane::Pointer(0); } return part.Cast()->GetPane(); } void* PartStack::GetParent() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()); } PartStack::PresentableVector PartStack::GetPresentableParts() { return presentableParts; } PresentablePart::Pointer PartStack::GetPresentablePart(LayoutPart::Pointer pane) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer part = iter->Cast(); if (part->GetPane() == pane) { return part; } } return PresentablePart::Pointer(0); } StackPresentation::Pointer PartStack::GetPresentation() { return presentationSite->GetPresentation(); } PartPane::Pointer PartStack::GetSelection() { if (PartPane::Pointer partPane = current.Cast()) { return partPane; } return PartPane::Pointer(0); } void PartStack::PresentationSelectionChanged(IPresentablePart::Pointer newSelection) { // Ignore selection changes that occur as a result of removing a part if (ignoreSelectionChanges) { return; } PartPane::Pointer newPart = this->GetPaneFor(newSelection); // This method should only be called on objects that are already in the layout poco_assert(newPart != 0); if (newPart == requestedCurrent) { return; } this->SetSelection(newPart); if (newPart != 0) { newPart->SetFocus(); } } void PartStack::Remove(LayoutPart::Pointer child) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(child); // Need to remove it from the list of children before notifying the presentation // since it may setVisible(false) on the part, leading to a partHidden notification, // during which findView must not find the view being removed. See bug 60039. children.removeAll(child); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { ignoreSelectionChanges = true; presentableParts.removeAll(presentablePart); presentation->RemovePart(presentablePart); presentablePart = 0; ignoreSelectionChanges = false; } if (this->GetPresentation() != 0) { child->SetContainer(ILayoutContainer::Pointer(0)); } if (child == requestedCurrent) { this->UpdateContainerVisibleTab(); } } void PartStack::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (tweaklet->GetParent(control) == newParent) || !tweaklet->IsReparentable(control)) { return; } LayoutPart::Reparent(newParent); for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->Reparent(newParent); } } void PartStack::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { ChildVector::iterator loc = std::find(children.begin(), children.end(), oldChild); int idx = 0; int numPlaceholders = 0; //subtract the number of placeholders still existing in the list //before this one - they wont have parts. for (ChildVector::iterator iter = children.begin(); iter != loc; ++iter, ++idx) { if ((*iter)->IsPlaceHolder()) { numPlaceholders++; } } ObjectInt::Pointer cookie(new ObjectInt(idx - numPlaceholders)); children.insert(loc, newChild); this->ShowPart(newChild, cookie); if (oldChild == requestedCurrent && newChild.Cast() != 0) { this->SetSelection(newChild.Cast()); } this->Remove(oldChild); } int PartStack::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return this->GetPresentation()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartStack::GetSizeFlags(bool horizontal) { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { return presentation->GetSizeFlags(horizontal); } return 0; } bool PartStack::RestoreState(IMemento::Pointer memento) { // Read the active tab. QString activeTabID; memento->GetString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, activeTabID); // Read the page elements. QList children = memento->GetChildren(WorkbenchConstants::TAG_PAGE); // Loop through the page elements. for (int i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; QString partID; childMem->GetString(WorkbenchConstants::TAG_CONTENT, partID); // Create the part. LayoutPart::Pointer part(new PartPlaceholder(partID)); part->SetContainer(ILayoutContainer::Pointer(this)); this->Add(part); //1FUN70C: ITPUI:WIN - Shouldn't set Container when not active //part.setContainer(this); if (partID == activeTabID) { this->SetSelection(part); // Mark this as the active part. //current = part; } } //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); int expanded; if (memento->GetInteger(WorkbenchConstants::TAG_EXPANDED, expanded)) { //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { SetState(expanded != IStackPresentationSite::STATE_MINIMIZED ? IStackPresentationSite::STATE_RESTORED : IStackPresentationSite::STATE_MINIMIZED); // } // }); } else { SetState(IStackPresentationSite::STATE_RESTORED); } int appearance; if (memento->GetInteger(WorkbenchConstants::TAG_APPEARANCE, appearance)) { this->appearance = appearance; } // Determine if the presentation has saved any info here savedPresentationState = 0; QList presentationMementos(memento ->GetChildren(WorkbenchConstants::TAG_PRESENTATION)); for (int idx = 0; idx < presentationMementos.size(); idx++) { IMemento::Pointer child = presentationMementos[idx]; QString id; child->GetString(WorkbenchConstants::TAG_ID, id); if (id == GetFactory()->GetId()) { savedPresentationState = child; break; } } IMemento::Pointer propertiesState = memento->GetChild(WorkbenchConstants::TAG_PROPERTIES); if (propertiesState) { QList props(propertiesState->GetChildren(WorkbenchConstants::TAG_PROPERTY)); for (int i = 0; i < props.size(); i++) { QString id = props[i]->GetID(); properties.insert(id, props[i]->GetTextData()); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } void PartStack::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); bool useShortcut = makeVisible || !isActive; if (ctrl != 0 && useShortcut) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } } if (makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } LayoutPart::SetVisible(makeVisible); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentation->SetVisible(makeVisible); } if (!makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(false); } } } bool PartStack::SaveState(IMemento::Pointer memento) { if (GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { // Save the active tab. if (requestedCurrent) { memento->PutString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, requestedCurrent->GetID()); } // Write out the presentable parts (in order) QSet cachedIds; PartStack::PresentableVector pparts(GetPresentableParts()); for (PartStack::PresentableVector::iterator ppIter = pparts.begin(); ppIter != pparts.end(); ++ppIter) { PresentablePart::Pointer presPart = ppIter->Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_PAGE); PartPane::Pointer part = presPart->GetPane(); QString tabText = part->GetPartReference()->GetPartName(); childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, presPart->GetPane()->GetPlaceHolderId()); // Cache the id so we don't write it out later cachedIds.insert(presPart->GetPane()->GetPlaceHolderId()); } for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer next = *iter; PartPane::Pointer part; if ((part = next.Cast())) { // Have we already written it out? if (cachedIds.find(part->GetPlaceHolderId()) != cachedIds.end()) continue; } IMemento::Pointer childMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); QString tabText = "LabelNotFound"; if (part) { tabText = part->GetPartReference()->GetPartName(); } childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, next->GetID()); } } // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { memento->PutInteger(WorkbenchConstants::TAG_EXPANDED, presentationSite->GetState()); // } // else // { // memento // .putInteger( // IWorkbenchConstants.TAG_EXPANDED, // (presentationSite.getState() == IStackPresentationSite.STATE_MINIMIZED) ? IStackPresentationSite.STATE_MINIMIZED // : IStackPresentationSite.STATE_RESTORED); // } memento->PutInteger(WorkbenchConstants::TAG_APPEARANCE, appearance); this->SavePresentationState(); if (savedPresentationState) { IMemento::Pointer presentationState = memento ->CreateChild(WorkbenchConstants::TAG_PRESENTATION); presentationState->PutMemento(savedPresentationState); } if (!properties.empty()) { IMemento::Pointer propertiesState = memento->CreateChild(WorkbenchConstants::TAG_PROPERTIES); for (QHash::iterator iterator = properties.begin(); iterator != properties.end(); ++iterator) { if (iterator.value().isEmpty()) continue; IMemento::Pointer prop = propertiesState->CreateChild(WorkbenchConstants::TAG_PROPERTY, iterator.key()); prop->PutTextData(iterator.value()); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); return true; } WorkbenchPage::Pointer PartStack::GetPage() { // WorkbenchWindow::Pointer window = this->GetWorkbenchWindow().Cast(); // // if (window == 0) // { // return 0; // } // // return window->GetActivePage().Cast(); return WorkbenchPage::Pointer(page); } void PartStack::SetActive(int activeState) { // if (activeState == StackPresentation::AS_ACTIVE_FOCUS && isMinimized) // { // setMinimized(false); // } presentationSite->SetActive(activeState); } int PartStack::GetActive() const { return presentationSite->GetActive(); } void PartStack::SetSelection(LayoutPart::Pointer part) { if (part == requestedCurrent) { return; } requestedCurrent = part; this->RefreshPresentationSelection(); } void PartStack::UpdateActions(PresentablePart::Pointer /*current*/) { } void PartStack::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); this->RefreshPresentationSelection(); } void PartStack::RefreshPresentationSelection() { // If deferring UI updates, exit. if (this->IsDeferred()) { return; } // If the presentation is already displaying the desired part, then there's nothing // to do. if (current == requestedCurrent) { return; } StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentationCurrent = this->GetPresentablePart(requestedCurrent); // this->UupdateActions(presentationCurrent); if (presentationCurrent != 0 && presentation != 0) { requestedCurrent->CreateControl(this->GetParent()); GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if (tweaklet->GetParent(requestedCurrent->GetControl()) != tweaklet->GetParent(this->GetControl())) { requestedCurrent->Reparent(tweaklet->GetParent(this->GetControl())); } presentation->SelectPart(presentationCurrent); } // Update the return value of getVisiblePart current = requestedCurrent; this->FireInternalPropertyChange(PROP_SELECTION); } } int PartStack::GetState() { return presentationSite->GetState(); } void PartStack::SetState(const int newState) { int oldState = presentationSite->GetState(); if (!this->SupportsState(newState) || newState == oldState) { return; } // WorkbenchWindow::Pointer wbw = this->GetPage()->GetWorkbenchWindow().Cast(); // if (wbw == 0 || wbw->GetShell() == 0 || wbw->GetActivePage() == 0) // return; // // WorkbenchPage::Pointer page = wbw->GetActivePage(); // // bool useNewMinMax = Perspective::UseNewMinMax(page->GetActivePerspective()); // // // we have to fiddle with the zoom behavior to satisfy Intro req's // // by usning the old zoom behavior for its stack // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // useNewMinMax = useNewMinMax; // && !this->IsIntroInStack(); // else if (newState == IStackPresentationSite::STATE_RESTORED) // { // PartStack::Pointer maxStack = page->GetActivePerspective()->GetPresentation()->GetMaximizedStack(); // useNewMinMax = useNewMinMax && maxStack == this; // } // // if (useNewMinMax) // { // //StartupThreading.runWithoutExceptions(new StartupRunnable() // // { // // void runWithException() throws Throwable // // { // wbw->GetPageComposite()->SetRedraw(false); // try // { // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartZoom(); // } // else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartUnzoom(); // } // // if (newState == IStackPresentationSite::STATE_MINIMIZED) // { // setMinimized(true); // } // // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // // } // catch (...) // { // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // } // // this->SetPresentationState(newState); // // } // // }); // } // else // { //// bool minimized = (newState == IStackPresentationSite::STATE_MINIMIZED); //// this->SetMinimized(minimized); //// //// if (newState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomIn(); //// } //// else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomOut(); //// //// if (newState == IStackPresentationSite::STATE_MINIMIZED) //// setMinimized(true); //// } // } } void PartStack::ShowPart(LayoutPart::Pointer part, Object::Pointer cookie) { if (this->GetPresentation() == 0) { return; } if (part->IsPlaceHolder()) { part->SetContainer(ILayoutContainer::Pointer(this)); return; } if (part.Cast() == 0) { WorkbenchPlugin::Log("Incorrect part " + part->GetID() + "contained in a part stack"); return; } PartPane::Pointer pane = part.Cast(); PresentablePart::Pointer presentablePart(new PresentablePart(pane, Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()))); presentableParts.push_back(presentablePart); if (isActive) { part->SetContainer(ILayoutContainer::Pointer(this)); // The active part should always be enabled if (part->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(part->GetControl(), true); } presentationSite->GetPresentation()->AddPart(presentablePart, cookie); if (requestedCurrent == 0) { this->SetSelection(pane); } // if (childObscuredByZoom(part)) // { // presentablePart.enableInputs(false); // } } void PartStack::UpdateContainerVisibleTab() { ChildVector parts = this->GetChildren(); if (parts.size() < 1) { this->SetSelection(LayoutPart::Pointer(0)); return; } PartPane::Pointer selPart; int topIndex = 0; WorkbenchPage::Pointer page = this->GetPage(); if (page != 0) { QList sortedParts = page->GetSortedParts(); for (ChildVector::iterator partIter = parts.begin(); partIter != parts.end(); ++partIter) { if (partIter->Cast() != 0) { IWorkbenchPartReference::Pointer part = partIter->Cast() ->GetPartReference(); int index = static_cast(std::find(sortedParts.begin(), sortedParts.end(), part) - sortedParts.begin()); if (index >= topIndex) { topIndex = index; selPart = partIter->Cast(); } } } } if (selPart == 0) { PresentableVector presentableParts = this->GetPresentableParts(); if (presentableParts.size() != 0) { IPresentablePart::Pointer part = presentableParts.front(); selPart = this->GetPaneFor(part); } } this->SetSelection(selPart); } void PartStack::ShowSystemMenu() { //this->GetPresentation()->ShowSystemMenu(); } void PartStack::ShowPaneMenu() { //this->GetPresentation()->ShowPaneMenu(); } void PartStack::ShowPartList() { this->GetPresentation()->ShowPartList(); } QList PartStack::GetTabList(LayoutPart::Pointer part) { if (part != 0) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(part); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { return presentation->GetTabList(presentablePart); } } return QList(); } -void PartStack::DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, +void PartStack::DragStart(IPresentablePart::Pointer beingDragged, QPoint& initialLocation, bool keyboard) { if (beingDragged == 0) { this->PaneDragStart(PartPane::Pointer(0), initialLocation, keyboard); } else { if (presentationSite->IsPartMoveable(beingDragged)) { PartPane::Pointer pane = this->GetPaneFor(beingDragged); if (pane != 0) { this->PaneDragStart(pane, initialLocation, keyboard); } } } } -void PartStack::PaneDragStart(PartPane::Pointer pane, Point& initialLocation, +void PartStack::PaneDragStart(PartPane::Pointer pane, QPoint& initialLocation, bool keyboard) { if (pane == 0) { if (this->CanMoveFolder()) { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage - Rectangle bounds = Geometry::ToDisplay(this->GetParent(), + QRect bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); - float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); - float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); + float xpct = (initialLocation.x() - bounds.x()) / (float)(bounds.width()); + float ypct = (initialLocation.y() - bounds.y()) / (float)(bounds.height()); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); - initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); - initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); + initialLocation.setX((int) (bounds.x() + (xpct * bounds.width()))); + initialLocation.setY((int) (bounds.y() + (ypct * bounds.height()))); } DragUtil::PerformDrag(Object::Pointer(this), Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } else { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage - Rectangle bounds = Geometry::ToDisplay(this->GetParent(), + QRect bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); - float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); - float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); + float xpct = (initialLocation.x() - bounds.x()) / (float)(bounds.width()); + float ypct = (initialLocation.y() - bounds.y()) / (float)(bounds.height()); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect // See bug 100908 bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); - initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); - initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); + initialLocation.setX((int) (bounds.x() + (xpct * bounds.width()))); + initialLocation.setY((int) (bounds.y() + (ypct * bounds.height()))); } DragUtil::PerformDrag(pane, Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } IMemento::Pointer PartStack::GetSavedPresentationState() { return savedPresentationState; } void PartStack::FireInternalPropertyChange(int id) { ObjectInt::Pointer val(new ObjectInt(id)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); propEvents.propertyChange(event); } QString PartStack::GetProperty(const QString& id) { return properties[id]; } void PartStack::SetProperty(const QString& id, const QString& value) { if (value == "") { properties.remove(id); } else { properties.insert(id, value); } } void PartStack::CopyAppearanceProperties(PartStack::Pointer copyTo) { copyTo->appearance = this->appearance; if (!properties.empty()) { for (QHash::iterator iter = properties.begin(); iter != properties.end(); ++iter) { copyTo->SetProperty(iter.key(), iter.value()); } } } void PartStack::ResizeChild(LayoutPart::Pointer /*childThatChanged*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.h index 54ff552817..f23b8663ed 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartStack.h @@ -1,760 +1,760 @@ /*=================================================================== 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 BERRYPARTSTACK_H_ #define BERRYPARTSTACK_H_ #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryWorkbenchPage.h" #include "berryPresentablePart.h" #include "berryPartPlaceholder.h" #include "berryDefaultStackPresentationSite.h" #include "berryPresentationFactoryUtil.h" #include "berryAbstractDropTarget.h" #include "berryPartPane.h" #include "berryIMemento.h" #include "presentations/berryIPresentationFactory.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Implements the common behavior for stacks of Panes (ie: EditorStack and ViewStack) * This layout container has PartPanes as children and belongs to a PartSashContainer. * * @since 3.0 */ class PartStack : public LayoutPart, public ILayoutContainer { friend class EditorSashContainer; friend class PartSashContainer; friend class DetachedWindow; public: berryObjectMacro(PartStack) public: static const int PROP_SELECTION; // = 0x42; private: typedef QList ChildVector; private: ChildVector children; private: WorkbenchPage* page; private: bool isActive; private: bool allowStateChanges; private: typedef QList PresentableVector; private: PresentableVector presentableParts; private: QHash properties; protected: int appearance; /** * Stores the last value passed to setSelection. If UI updates are being deferred, * this may be significantly different from the other current pointers. Once UI updates * are re-enabled, the stack will update the presentation selection to match the requested * current pointer. */ private: LayoutPart::Pointer requestedCurrent; /** * Stores the current part for the stack. Whenever the outside world asks a PartStack * for the current part, this is what gets returned. This pointer is only updated after * the presentation selection has been restored and the stack has finished updating its * internal state. If the stack is still in the process of updating the presentation, * it will still point to the previous part until the presentation is up-to-date. */ private: LayoutPart::Pointer current; /** * Stores the presentable part sent to the presentation. Whenever the presentation * asks for the current part, this is what gets returned. This is updated before sending * the part to the presentation, and it is not updated while UI updates are disabled. * When UI updates are enabled, the stack first makes presentationCurrent match * requestedCurrent. Once the presentation is displaying the correct part, the "current" * pointer on PartStack is updated. */ private: PresentablePart::Pointer presentationCurrent; private: bool ignoreSelectionChanges; protected: IMemento::Pointer savedPresentationState; protected: class MyStackPresentationSite : public DefaultStackPresentationSite { private: PartStack* partStack; public: MyStackPresentationSite(PartStack* stack); void Close(IPresentablePart::Pointer part); void Close(const QList& parts); void DragStart(IPresentablePart::Pointer beingDragged, - Point& initialLocation, bool keyboard); + QPoint& initialLocation, bool keyboard); - void DragStart(Point& initialLocation, bool keyboard); + void DragStart(QPoint& initialLocation, bool keyboard); bool IsPartMoveable(IPresentablePart::Pointer part); void SelectPart(IPresentablePart::Pointer toSelect); bool SupportsState(int state); void SetState(int newState); IPresentablePart::Pointer GetSelectedPart(); // void AddSystemActions(IMenuManager menuManager) { // PartStack.this.addSystemActions(menuManager); // } bool IsStackMoveable(); void FlushLayout(); PresentableVector GetPartList(); QString GetProperty(const QString& id); }; DefaultStackPresentationSite::Pointer presentationSite; private: class PartStackDropResult : public AbstractDropTarget { private: PartPane::WeakPtr pane; // Result of the presentation's dragOver method or null if we are stacking over the // client area of the pane. StackDropResult::Pointer dropResult; PartStack::WeakPtr stack; public: berryObjectMacro(PartStackDropResult) /** * Resets the target of this drop result (allows the same drop result object to be * reused) * * @param stack * @param pane * @param result result of the presentation's dragOver method, or null if we are * simply stacking anywhere. * @since 3.1 */ void SetTarget(PartStack::Pointer stack, PartPane::Pointer pane, StackDropResult::Pointer result); void Drop(); - DnDTweaklet::CursorType GetCursor(); + CursorType GetCursor(); - Rectangle GetSnapRectangle(); + QRect GetSnapRectangle(); }; private: static PartStackDropResult::Pointer dropResult; // protected: bool isMinimized; private: IPropertyChangeListener::Events propEvents; /** * Custom presentation factory to use for this stack, or null to * use the default */ private: IPresentationFactory* factory; // private: boolean smartZoomed = false; // private: boolean doingUnzoom = false; protected: virtual bool IsMoveable(IPresentablePart::Pointer part); // protected: abstract void addSystemActions(IMenuManager menuManager); protected: virtual bool SupportsState(int newState); protected: virtual bool CanMoveFolder(); protected: virtual void DerefPart(LayoutPart::Pointer toDeref); protected: virtual bool AllowsDrop(PartPane::Pointer part); // protected: static void appendToGroupIfPossible(IMenuManager m, // String groupId, ContributionItem item) { // try { // m.appendToGroup(groupId, item); // } catch (IllegalArgumentException e) { // m.add(item); // } // } /** * Creates a new part stack that uses the given custom presentation factory * @param appearance * @param factory custom factory to use (or null to use the default) */ public: PartStack(WorkbenchPage* page, bool allowsStateChanges = true, int appearance = PresentationFactoryUtil::ROLE_VIEW, IPresentationFactory* factory = 0); /** * Adds a property listener to this stack. The listener will receive a PROP_SELECTION * event whenever the result of getSelection changes * * @param listener */ public: void AddListener(IPropertyChangeListener* listener); public: void RemoveListener(IPropertyChangeListener* listener); public: int GetAppearance() const; public: QString GetID() const; protected: bool IsStandalone(); /** * Returns the currently selected IPresentablePart, or null if none * * @return */ protected: IPresentablePart::Pointer GetSelectedPart(); protected: IStackPresentationSite::Pointer GetPresentationSite(); /** * Tests the integrity of this object. Throws an exception if the object's state * is invalid. For use in test suites. */ public: void TestInvariants(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#describeLayout(java.lang.StringBuffer) */ public: void DescribeLayout(QString& buf) const; /** * See IVisualContainer#add */ public: void Add(LayoutPart::Pointer child); /** * Add a part at a particular position */ protected: void Add(LayoutPart::Pointer newChild, Object::Pointer cookie); public: bool AllowsAdd(LayoutPart::Pointer toAdd); /* * (non-Javadoc) * * @see org.blueberry.ui.internal.ILayoutContainer#allowsAutoFocus() */ public: bool AllowsAutoFocus(); /** * @param parts */ protected: void Close(const QList& parts); /** * @param part */ protected: void Close(IPresentablePart::Pointer part); protected: IPresentationFactory* GetFactory(); public: void CreateControl(void* parent); /* (non-Javadoc) - * @see org.blueberry.ui.internal.LayoutPart#getDropTarget(java.lang.Object, org.blueberry.swt.graphics.Point) + * @see org.blueberry.ui.internal.LayoutPart#getDropTarget(java.lang.Object, org.blueberry.swt.graphics.QPoint) */ - public: IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const Point& position); + public: IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const QPoint& position); public: void SetActive(bool isActive); public: IDropTarget::Pointer CreateDropTarget(PartPane::Pointer pane, StackDropResult::Pointer result); /** * Saves the current state of the presentation to savedPresentationState, if the * presentation exists. */ protected: void SavePresentationState(); public: ~PartStack(); /** * See LayoutPart#Dispose */ public: void Dispose(); public: void FindSashes(LayoutPart::Pointer toFind, PartPane::Sashes& sashes); /** * Gets the presentation bounds. */ - public: Rectangle GetBounds(); + public: QRect GetBounds(); /** * See IVisualContainer#getChildren */ public: ChildVector GetChildren() const; public: void* GetControl(); /** * Answer the number of children. */ public: ChildVector::size_type GetItemCount(); /** * Returns the LayoutPart for the given IPresentablePart, or null if the given * IPresentablePart is not in this stack. Returns null if given a null argument. * * @param part to locate or null * @return */ protected: PartPane::Pointer GetPaneFor(IPresentablePart::Pointer part); /** * Get the parent control. */ public: void* GetParent(); /** * Returns a list of IPresentablePart * * @return */ public: PresentableVector GetPresentableParts(); private: PresentablePart::Pointer GetPresentablePart(LayoutPart::Pointer pane); protected: StackPresentation::Pointer GetPresentation(); /** * Returns the visible child. * @return the currently visible part, or null if none */ public: PartPane::Pointer GetSelection(); private: void PresentationSelectionChanged(IPresentablePart::Pointer newSelection); /** * See IVisualContainer#remove */ public: void Remove(LayoutPart::Pointer child); /** * Reparent a part. Also reparent visible children... */ public: void Reparent(void* newParent); /** * See IVisualContainer#replace */ public: void Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#computePreferredSize(boolean, int, int, int) */ public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getSizeFlags(boolean) */ public: int GetSizeFlags(bool horizontal); /** * @see IPersistable */ public: bool RestoreState(IMemento::Pointer memento); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setVisible(boolean) */ public: void SetVisible(bool makeVisible); /** * @see IPersistable */ public: bool SaveState(IMemento::Pointer memento); protected: WorkbenchPage::Pointer GetPage(); /** * Set the active appearence on the tab folder. * * @param active */ public: void SetActive(int activeState); public: int GetActive() const; public: void CreateControl(void* parent, StackPresentation::Pointer presentation); /** * Sets the presentation bounds. */ - public: void SetBounds(const Rectangle& r); + public: void SetBounds(const QRect& r); public: void SetSelection(LayoutPart::Pointer part); /** * Updates the enablement state of actions */ protected: virtual void UpdateActions(PresentablePart::Pointer current); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#handleDeferredEvents() */ protected: void HandleDeferredEvents(); private: void RefreshPresentationSelection(); public: int GetState(); /** * Sets the minimized state for this stack. The part may call this method to * minimize or restore itself. The minimized state only affects the view * when unzoomed in the 3.0 presentation (in 3.3 it's handled by the * ViewStack directly and works as expected). */ // public: void setMinimized(boolean minimized) { // if (minimized != isMinimized) { // isMinimized = minimized; // // refreshPresentationState(); // } // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#obscuredByZoom(org.blueberry.ui.internal.LayoutPart) */ // public: boolean childObscuredByZoom(LayoutPart toTest) { // return isObscuredByZoom(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#requestZoom(org.blueberry.ui.internal.LayoutPart) */ // public: void childRequestZoomIn(LayoutPart toZoom) { // super.childRequestZoomIn(toZoom); // // requestZoomIn(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#requestZoomOut() */ // public: void childRequestZoomOut() { // super.childRequestZoomOut(); // // requestZoomOut(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#isZoomed(org.blueberry.ui.internal.LayoutPart) */ // public: boolean childIsZoomed(LayoutPart toTest) { // return isZoomed(); // } /** * This is a hack that allows us to preserve the old * min/max behavior for the stack containing the IntroPart. * This is required to have the initial Intro (Welcome) * pane to show correctly but will induce strange * effects should a user re-locate the part to * stacks other that its initial one... * * @return true if the stack contains the intro * as a ViewPane (not if it's only a placeholder) */ // private: boolean isIntroInStack() { // LayoutPart[] kids = getChildren(); // for (int i = 0; i < kids.length; i++) { // if (kids[i] instanceof ViewPane) { // ViewPane vp = (ViewPane) kids[i]; // if (vp.getID().equals(IIntroConstants.INTRO_VIEW_ID)) // return true; // } // } // return false; // } // private: void smartZoom() { // WorkbenchWindow wbw = (WorkbenchWindow) getPage().getWorkbenchWindow(); // if (wbw == null || wbw.getShell() == null) // return; // // Perspective perspective = getPage().getActivePerspective(); // FastViewManager fvm = perspective.getFastViewManager(); // // fvm.deferUpdates(true); // // // Cache the layout bounds // perspective.getPresentation().updateBoundsMap(); // // LayoutPart[] children = perspective.getPresentation().getLayout().getChildren(); // for (int i = 0; i < children.length; i++) { // if (children[i] != this) { // if (children[i] instanceof ViewStack) { // ((ViewStack) children[i]).setMinimized(true); // ViewStackTrimToolBar vstb = fvm // .getViewStackTrimToolbar(children[i] // .getID()); // vstb.setRestoreOnUnzoom(true); // } // else if (children[i] instanceof EditorSashContainer && !(this instanceof EditorStack)) { // perspective.setEditorAreaState(IStackPresentationSite.STATE_MINIMIZED); // perspective.setEditorAreaRestoreOnUnzoom(true); // } // } // } // // // If the editor area has changed state tell the perspective // if (this instanceof EditorStack) // perspective.setEditorAreaState(IStackPresentationSite.STATE_MAXIMIZED); // // // Clear the boundsMap // perspective.getPresentation().resetBoundsMap(); // // // We're done batching... // fvm.deferUpdates(false); // // perspective.getPresentation().setMaximizedStack(this); // smartZoomed = true; // } // protected: void smartUnzoom() { // // Prevent recursion through 'setMinimized' // if (doingUnzoom) // return; // doingUnzoom = true; // // WorkbenchWindow wbw = (WorkbenchWindow) getPage().getWorkbenchWindow(); // if (wbw == null || wbw.getShell() == null) // return; // // ITrimManager tbm = wbw.getTrimManager(); // Perspective perspective = getPage().getActivePerspective(); // FastViewManager fvm = perspective.getFastViewManager(); // // ILayoutContainer root = getContainer(); // // // We go up one more level when maximizing an editor stack // // so that we 'zoom' the editor area // boolean restoringEditorArea = false; // if (root instanceof EditorSashContainer) { // root = ((EditorSashContainer) root).getContainer(); // restoringEditorArea = true; // } // // // This is a compound operation // fvm.deferUpdates(true); // // LayoutPart[] children = root.getChildren(); // for (int i = 0; i < children.length; i++) { // if (children[i] != this) { // IWindowTrim trim = tbm.getTrim(children[i].getID()); // if (trim == null) // continue; // // if (trim instanceof ViewStackTrimToolBar) { // ViewStackTrimToolBar vstb = (ViewStackTrimToolBar) trim; // if (vstb.restoreOnUnzoom() // && children[i] instanceof ContainerPlaceholder) { // // In the current presentation its a // // container placeholder // ViewStack realStack = (ViewStack) ((ContainerPlaceholder) children[i]) // .getRealContainer(); // realStack.setMinimized(false); // // vstb.setRestoreOnUnzoom(false); // } // } else if (trim instanceof EditorAreaTrimToolBar) { // if (perspective.getEditorAreaRestoreOnUnzoom()) // perspective.setEditorAreaState(IStackPresentationSite.STATE_RESTORED); // } // } // } // // // If the editor area has changed state tell the perspective // if (restoringEditorArea) // perspective.setEditorAreaState(IStackPresentationSite.STATE_RESTORED); // // perspective.getPresentation().setMaximizedStack(null); // // fvm.deferUpdates(false); // smartZoomed = false; // // doingUnzoom = false; // } protected: void SetState(const int newState); /** * Called by the workbench page to notify this part that it has been zoomed or unzoomed. * The PartStack should not call this method itself -- it must request zoom changes by * talking to the WorkbenchPage. */ // public: void setZoomed(boolean isZoomed) { // // super.setZoomed(isZoomed); // // LayoutPart[] children = getChildren(); // // for (int i = 0; i < children.length; i++) { // LayoutPart next = children[i]; // // next.setZoomed(isZoomed); // } // // refreshPresentationState(); // } // public: boolean isZoomed() { // ILayoutContainer container = getContainer(); // // if (container != null) { // return container.childIsZoomed(this); // } // // return false; // } // protected: void refreshPresentationState() { // if (isZoomed() || smartZoomed) { // presentationSite.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } else { // // boolean wasMinimized = (presentationSite.getState() == IStackPresentationSite.STATE_MINIMIZED); // // if (isMinimized) { // presentationSite.setPresentationState(IStackPresentationSite.STATE_MINIMIZED); // } else { // presentationSite.setPresentationState(IStackPresentationSite.STATE_RESTORED); // } // // if (isMinimized != wasMinimized) { // flushLayout(); // // if (isMinimized) { // WorkbenchPage page = getPage(); // // if (page != null) { // page.refreshActiveView(); // } // } // } // } // } /** * Makes the given part visible in the presentation. * @param part the part to add to the stack * @param cookie other information */ private: void ShowPart(LayoutPart::Pointer part, Object::Pointer cookie); /** * Update the container to show the correct visible tab based on the * activation list. */ private: void UpdateContainerVisibleTab(); /** * */ public: void ShowSystemMenu(); public: void ShowPaneMenu(); public: void ShowPartList(); public: QList GetTabList(LayoutPart::Pointer part); /** * * @param beingDragged * @param initialLocation * @param keyboard */ - private: void DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, + private: void DragStart(IPresentablePart::Pointer beingDragged, QPoint& initialLocation, bool keyboard); - public: void PaneDragStart(PartPane::Pointer pane, Point& initialLocation, + public: void PaneDragStart(PartPane::Pointer pane, QPoint& initialLocation, bool keyboard); /** * @return Returns the savedPresentationState. */ public: IMemento::Pointer GetSavedPresentationState(); private: void FireInternalPropertyChange(int id); // TrimStack Support /** * Explicitly sets the presentation state. This is used by the * new min/max code to force the CTabFolder to show the proper * state without going through the 'setState' code (which causes * nasty side-effects. * @param newState The state to set the presentation to */ // public: void setPresentationState(int newState) { // presentationSite.setPresentationState(newState); // } // // Support for passing perspective layout properties to the presentation public: QString GetProperty(const QString& id); public: void SetProperty(const QString& id, const QString& value); /** * Copies all appearance related data from this stack to the given stack. */ public: void CopyAppearanceProperties(PartStack::Pointer copyTo); public: void ResizeChild(LayoutPart::Pointer childThatChanged); }; } #endif /*BERRYPARTSTACK_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp index 99b5125b50..65694e00d9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp @@ -1,1812 +1,1813 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveExtensionReader.h" #include "berryEditorSashContainer.h" #include "berryPartSite.h" #include "berryViewSite.h" #include "berryEditorAreaHelper.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchWindow.h" #include "berryStatusUtil.h" #include "presentations/berryIStackPresentationSite.h" #include namespace berry { const QString Perspective::VERSION_STRING = "0.016"; Perspective::Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page) : descriptor(desc) { this->Init(page); if (desc.IsNotNull()) { this->CreatePresentation(desc); } } Perspective::Perspective(WorkbenchPage::Pointer page) { this->Init(page); } void Perspective::Init(WorkbenchPage::Pointer page) { editorHidden = false; editorAreaState = IStackPresentationSite::STATE_RESTORED; fixed = false; presentation = 0; shouldHideEditorsOnActivate = false; this->page = page.GetPointer(); this->editorArea = page->GetEditorPresentation()->GetLayoutPart(); this->viewFactory = page->GetViewFactory(); } bool Perspective::BringToTop(IViewReference::Pointer ref) { return presentation->BringPartToTop(this->GetPane(ref)); } bool Perspective::ContainsView(IViewPart::Pointer view) { IViewSite::Pointer site = view->GetViewSite(); IViewReference::Pointer ref = this->FindView(site->GetId(), site->GetSecondaryId()); if (ref.IsNull()) { return false; } return (view.Cast() == ref->GetPart(false)); } bool Perspective::ContainsView(const QString& viewId) const { return mapIDtoViewLayoutRec.contains(viewId); } void Perspective::CreatePresentation(PerspectiveDescriptor::Pointer persp) { if (persp->HasCustomDefinition()) { this->LoadCustomPersp(persp); } else { this->LoadPredefinedPersp(persp); } } Perspective::~Perspective() { // Get rid of presentation. if (presentation == 0) { DisposeViewRefs(); return; } presentation->Deactivate(); // Release each view. QList refs(this->GetViewReferences()); for (QList::size_type i = 0, length = refs.size(); i < length; i++) { this->GetViewFactory()->ReleaseView(refs[i]); } mapIDtoViewLayoutRec.clear(); delete presentation; } void Perspective::DisposeViewRefs() { if (!memento) { return; } QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId = ViewFactory::ExtractSecondaryId(id); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } QString removed; childMem->GetString(WorkbenchConstants::TAG_REMOVED, removed); if (removed != "true") { IViewReference::Pointer ref = viewFactory->GetView(id, secondaryId); if (ref) { viewFactory->ReleaseView(ref); } } } } IViewReference::Pointer Perspective::FindView(const QString& viewId) { return this->FindView(viewId, ""); } IViewReference::Pointer Perspective::FindView(const QString& id, const QString& secondaryId) { QList refs(this->GetViewReferences()); for (int i = 0; i < refs.size(); i++) { IViewReference::Pointer ref = refs[i]; if (id == ref->GetId() && (secondaryId == ref->GetSecondaryId())) { return ref; } } return IViewReference::Pointer(0); } void* Perspective::GetClientComposite() { return page->GetClientComposite(); } IPerspectiveDescriptor::Pointer Perspective::GetDesc() { return descriptor; } PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref) { return ref.Cast()->GetPane(); } QList Perspective::GetPerspectiveShortcuts() { return perspectiveShortcuts; } PerspectiveHelper* Perspective::GetPresentation() const { return presentation; } QList Perspective::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* Perspective::GetViewFactory() { return viewFactory; } QList Perspective::GetViewReferences() { // Get normal views. if (presentation == 0) { return QList(); } QList panes; presentation->CollectViewPanes(panes); QList result; // List fastViews = (fastViewManager != 0) ? // fastViewManager.getFastViews(0) // : new ArrayList(); // IViewReference[] resultArray = new IViewReference[panes.size() // + fastViews.size()]; // // // Copy fast views. // int nView = 0; // for (int i = 0; i < fastViews.size(); i++) // { // resultArray[nView] = (IViewReference) fastViews.get(i); // ++nView; // } // Copy normal views. for (QList::iterator iter = panes.begin(); iter != panes.end(); ++iter) { PartPane::Pointer pane = *iter; result.push_back(pane->GetPartReference().Cast()); } return result; } void Perspective::HideEditorArea() { if (!this->IsEditorAreaVisible()) { return; } // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { // If it's the currently maximized part we have to restore first // if (this->GetPresentation().getMaximizedStack().Cast() != 0) // { // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) this->HideEditorAreaLocal(); //else // this->SetEditorAreaTrimVisibility(false); } else { this->HideEditorAreaLocal(); } editorHidden = true; } void Perspective::HideEditorAreaLocal() { if (editorHolder != 0) { return; } // Replace the editor area with a placeholder so we // know where to put it back on show editor area request. editorHolder = new PartPlaceholder(editorArea->GetID()); presentation->GetLayout()->Replace(editorArea, editorHolder); } bool Perspective::HideView(IViewReference::Pointer ref) { // If the view is locked just return. PartPane::Pointer pane = this->GetPane(ref); presentation->RemovePart(pane); // Dispose view if ref count == 0. this->GetViewFactory()->ReleaseView(ref); return true; } bool Perspective::IsEditorAreaVisible() { return !editorHidden; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(IViewReference::Pointer ref, bool create) { ViewLayoutRec::Pointer result = this->GetViewLayoutRec(ViewFactory::GetKey(ref), create); if (result.IsNull() && create==false) { result = this->GetViewLayoutRec(ref->GetId(), false); } return result; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(const QString& viewId, bool create) { ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[viewId]; if (rec.IsNull() && create) { rec = new ViewLayoutRec(); mapIDtoViewLayoutRec[viewId] = rec; } return rec; } bool Perspective::IsFixedLayout() { //@issue is there a difference between a fixed //layout and a fixed perspective?? If not the API //may need some polish, WorkbenchPage, PageLayout //and Perspective all have isFixed methods. //PageLayout and Perspective have their own fixed //attribute, we are assuming they are always in sync. //WorkbenchPage delegates to the perspective. return fixed; } bool Perspective::IsStandaloneView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->isStandalone; } bool Perspective::GetShowTitleView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->showTitle; } void Perspective::LoadCustomPersp(PerspectiveDescriptor::Pointer persp) { //get the layout from the registry PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); try { IMemento::Pointer memento = perspRegistry->GetCustomPersp(persp->GetId()); // Restore the layout state. // MultiStatus status = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()), // 0); // status.merge(restoreState(memento)); // status.merge(restoreState()); bool okay = true; okay &= this->RestoreState(memento); okay &= this->RestoreState(); if (!okay) { this->UnableToOpenPerspective(persp, "Unable to open perspective: " + persp->GetLabel()); } } //catch (IOException e) //{ // unableToOpenPerspective(persp, 0); //} catch (const WorkbenchException& e) { this->UnableToOpenPerspective(persp, e.what()); } } void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status) { PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin ::GetDefault()->GetPerspectiveRegistry()); perspRegistry->DeletePerspective(persp); // If this is a predefined perspective, we will not be able to delete // the perspective (we wouldn't want to). But make sure to delete the // customized portion. persp->DeleteCustomDefinition(); QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; if (status == "") { QMessageBox::critical(NULL, title, msg); } else { //TODO error dialog //ErrorDialog.openError((Shell) 0, title, msg, status); QMessageBox::critical(NULL, title, msg + "\n" + status); } } void Perspective::LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp) { // Create layout engine. IPerspectiveFactory::Pointer factory; try { factory = persp->CreateFactory(); } catch (CoreException& /*e*/) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } /* * IPerspectiveFactory#createFactory() can return 0 */ if (factory == 0) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } // Create layout factory. ViewSashContainer::Pointer container(new ViewSashContainer(page, this->GetClientComposite())); layout = new PageLayout(container, this->GetViewFactory(), editorArea, descriptor); layout->SetFixed(descriptor->GetFixed()); // // add the placeholders for the sticky folders and their contents IPlaceholderFolderLayout::Pointer stickyFolderRight, stickyFolderLeft, stickyFolderTop, stickyFolderBottom; QList descs(WorkbenchPlugin::GetDefault() ->GetViewRegistry()->GetStickyViews()); for (int i = 0; i < descs.size(); i++) { IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i]; QString id = stickyViewDescriptor->GetId(); int location = stickyViewDescriptor->GetLocation(); if (location == IPageLayout::RIGHT) { if (stickyFolderRight == 0) { stickyFolderRight = layout ->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_RIGHT, IPageLayout::RIGHT, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderRight->AddPlaceholder(id); } else if (location == IPageLayout::LEFT) { if (stickyFolderLeft == 0) { stickyFolderLeft = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_LEFT, IPageLayout::LEFT, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderLeft->AddPlaceholder(id); } else if (location == IPageLayout::TOP) { if (stickyFolderTop == 0) { stickyFolderTop = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_TOP, IPageLayout::TOP, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderTop->AddPlaceholder(id); } else if (location == IPageLayout::BOTTOM) { if (stickyFolderBottom == 0) { stickyFolderBottom = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_BOTTOM, IPageLayout::BOTTOM, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderBottom->AddPlaceholder(id); } //should never be 0 as we've just added the view above IViewLayout::Pointer viewLayout = layout->GetViewLayout(id); viewLayout->SetCloseable(stickyViewDescriptor->IsCloseable()); viewLayout->SetMoveable(stickyViewDescriptor->IsMoveable()); } // Run layout engine. factory->CreateInitialLayout(layout); PerspectiveExtensionReader extender; extender.ExtendLayout(descriptor->GetId(), layout); // Retrieve view layout info stored in the page layout. QHash layoutInfo = layout->GetIDtoViewLayoutRecMap(); mapIDtoViewLayoutRec.unite(layoutInfo); //TODO Perspective action sets // Create action sets. //List temp = new ArrayList(); //this->CreateInitialActionSets(temp, layout.getActionSets()); // IContextService service = 0; // if (page != 0) // { // service = (IContextService) page.getWorkbenchWindow().getService( // IContextService.class); // } // try // { // if (service!=0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // for (Iterator iter = temp.iterator(); iter.hasNext();) // { // IActionSetDescriptor descriptor = (IActionSetDescriptor) iter // .next(); // addAlwaysOn(descriptor); // } // }finally // { // if (service!=0) // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // newWizardShortcuts = layout.getNewWizardShortcuts(); showViewShortcuts = layout->GetShowViewShortcuts(); // perspectiveShortcuts = layout.getPerspectiveShortcuts(); // showInPartIds = layout.getShowInPartIds(); // // // Retrieve fast views // if (fastViewManager != 0) // { // ArrayList fastViews = layout.getFastViews(); // for (Iterator fvIter = fastViews.iterator(); fvIter.hasNext();) // { // IViewReference ref = (IViewReference) fvIter.next(); // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, // !fvIter.hasNext()); // } // } // Is the layout fixed fixed = layout->IsFixed(); showViewShortcuts = layout->GetShowViewShortcuts(); // Create presentation. presentation = new PerspectiveHelper(page, container, this); // Hide editor area if requested by factory if (!layout->IsEditorAreaVisible()) { this->HideEditorArea(); } } void Perspective::OnActivate() { // Update editor area state. if (editorArea->GetControl() != 0) { bool visible = this->IsEditorAreaVisible(); bool inTrim = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; editorArea->SetVisible(visible && !inTrim); } // // Update fast views. // // Make sure the control for the fastviews are created so they can // // be activated. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl == 0) // { // pane.createControl(getClientComposite()); // ctrl = pane.getControl(); // } // ctrl.setEnabled(false); // Remove focus support. // } // } // } // // Set the visibility of all fast view pins // setAllPinsVisible(true); // Trim Stack Support bool useNewMinMax = Perspective::UseNewMinMax(Perspective::Pointer(this)); bool hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == 0); // We have to set the editor area's stack state -before- // activating the presentation since it's used there to determine // size of the resulting stack if (useNewMinMax && !hideEditorArea) { this->RefreshEditorAreaVisibility(); } // Show the layout presentation->Activate(this->GetClientComposite()); // if (useNewMinMax) // { // fastViewManager.activate(); // // // Move any minimized extension stacks to the trim // if (layout != 0) // { // // Turn aimations off // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useAnimations = preferenceStore // .getbool(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS); // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false); // // List minStacks = layout.getMinimizedStacks(); // for (Iterator msIter = minStacks.iterator(); msIter.hasNext();) // { // ViewStack vs = (ViewStack) msIter.next(); // vs.setMinimized(true); // } // // // Restore the animation pref // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations); // // // this is a one-off deal...set during the extension reading // minStacks.clear(); // layout = 0; // } // } // else // { // // Update the FVB only if not using the new min/max // // // WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow(); //// if (wbw != 0) //// { //// ITrimManager tbm = wbw.getTrimManager(); //// if (tbm != 0) //// { //// IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID); //// if (fvb instanceof FastViewBar) //// { //// ((FastViewBar)fvb).update(true); //// } //// } //// } // } // // If we are -not- using the new min/max then ensure that there // // are no stacks in the trim. This can happen when a user switches // // back to the 3.0 presentation... // if (!Perspective.useNewMinMax(this) && fastViewManager != 0) // { // bool stacksWereRestored = fastViewManager.restoreAllTrimStacks(); // setEditorAreaTrimVisibility(false); // // // Restore any 'maximized' view stack since we've restored // // the minimized stacks // if (stacksWereRestored && presentation.getMaximizedStack().Cast() != 0) // { // ViewStack vs = (ViewStack) presentation.getMaximizedStack(); // vs.setPresentationState(IStackPresentationSite.STATE_RESTORED); // presentation.setMaximizedStack(0); // } // } // We hide the editor area -after- the presentation activates if (hideEditorArea) { // We do this here to ensure that createPartControl is called on the // top editor // before it is hidden. See bug 20166. this->HideEditorArea(); shouldHideEditorsOnActivate = false; // // this is an override so it should handle both states // if (useNewMinMax) // setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED); } FixOrphan(); } void Perspective::FixOrphan() { PerspectiveRegistry* reg = static_cast(PlatformUI::GetWorkbench()->GetPerspectiveRegistry()); IPerspectiveDescriptor::Pointer regDesc = reg->FindPerspectiveWithId(descriptor->GetId()); if (regDesc.IsNull()) { QString msg = "Perspective " + descriptor->GetLabel() + " has been made into a local copy"; IStatus::Pointer status = StatusUtil::NewStatus(IStatus::WARNING_TYPE, msg, BERRY_STATUS_LOC); //StatusManager.getManager().handle(status, StatusManager.LOG); WorkbenchPlugin::Log(status); QString localCopyLabel("<%1>"); QString newDescId = localCopyLabel.arg(descriptor->GetLabel()); while (reg->FindPerspectiveWithId(newDescId).IsNotNull()) { newDescId = localCopyLabel.arg(newDescId); } IPerspectiveDescriptor::Pointer newDesc = reg->CreatePerspective(newDescId, descriptor); page->SavePerspectiveAs(newDesc); } } void Perspective::OnDeactivate() { presentation->Deactivate(); //setActiveFastView(0); //setAllPinsVisible(false); // // Update fast views. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl != 0) // { // ctrl.setEnabled(true); // Add focus support. // } // } // } // // fastViewManager.deActivate(); // } // // // Ensure that the editor area trim is hidden as well // setEditorAreaTrimVisibility(false); } void Perspective::PartActivated(IWorkbenchPart::Pointer /*activePart*/) { // // If a fastview is open close it. // if (activeFastView != 0 // && activeFastView.getPart(false) != activePart) // { // setActiveFastView(0); // } } void Perspective::PerformedShowIn(const QString& /*partId*/) { //showInTimes.insert(std::make_pair(partId, new Long(System.currentTimeMillis()))); } bool Perspective::RestoreState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; // Create persp descriptor. descriptor = new PerspectiveDescriptor("", "", PerspectiveDescriptor::Pointer(0)); //result.add(descriptor.restoreState(memento)); result &= descriptor->RestoreState(memento); PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->FindPerspectiveWithId(descriptor->GetId()).Cast(); if (desc) { descriptor = desc; } else { try { WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->CreatePerspective(descriptor->GetLabel(), descriptor.Cast()); } catch (...) { std::cout << "Perspective could not be loaded" << std::endl; } } this->memento = memento; // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); //result.merge(createReferences(views)); result &= this->CreateReferences(views); memento = memento->GetChild(WorkbenchConstants::TAG_FAST_VIEWS); if (memento) { views = memento->GetChildren(WorkbenchConstants::TAG_VIEW); //result.merge(createReferences(views)); result &= this->CreateReferences(views); } return result; } bool Perspective::CreateReferences(const QList& views) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringViews, 0); bool result = true; for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // Create and open the view. try { QString rm; childMem->GetString(WorkbenchConstants::TAG_REMOVED, rm); if (rm != "true") { viewFactory->CreateView(id, secondaryId); } } catch (const PartInitException& e) { childMem->PutString(WorkbenchConstants::TAG_REMOVED, "true"); // result.add(StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e)); WorkbenchPlugin::Log(e.what(), e); result &= true; } } return result; } bool Perspective::RestoreState() { if (this->memento == 0) { //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; IMemento::Pointer memento = this->memento; this->memento = 0; const IMemento::Pointer boundsMem(memento->GetChild(WorkbenchConstants::TAG_WINDOW)); if (boundsMem) { - Rectangle r(0, 0, 0, 0); - boundsMem->GetInteger(WorkbenchConstants::TAG_X, r.x); - boundsMem->GetInteger(WorkbenchConstants::TAG_Y, r.y); - boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, r.height); - boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, r.width); + int x, y, w, h; + boundsMem->GetInteger(WorkbenchConstants::TAG_X, x); + boundsMem->GetInteger(WorkbenchConstants::TAG_Y, y); + boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, h); + boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, w); + QRect r(x, y, w, h); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { if (page->GetWorkbenchWindow()->GetActivePage() == 0) { page->GetWorkbenchWindow()->GetShell()->SetBounds(r); } // } // }); } // Create an empty presentation.. PerspectiveHelper* pres; //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { ViewSashContainer::Pointer mainLayout(new ViewSashContainer(page, this->GetClientComposite())); pres = new PerspectiveHelper(page, mainLayout, this); // }}); // Read the layout. // result.merge(pres.restoreState(memento // .getChild(IWorkbenchConstants.TAG_LAYOUT))); result &= pres->RestoreState(memento->GetChild(WorkbenchConstants::TAG_LAYOUT)); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // Add the editor workbook. Do not hide it now. pres->ReplacePlaceholderWithPart(editorArea); // }}); // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // skip the intro as it is restored higher up in workbench. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } // Create and open the view. IViewReference::Pointer viewRef = viewFactory->GetView(id, secondaryId); WorkbenchPartReference::Pointer ref = viewRef.Cast(); // report error if (ref == 0) { QString key = ViewFactory::GetKey(id, secondaryId); // result.add(new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, // NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), 0)); WorkbenchPlugin::Log("Could not find view: " + key); continue; } bool willPartBeVisible = pres->WillPartBeVisible(ref->GetId(), secondaryId); if (willPartBeVisible) { IViewPart::Pointer view = ref->GetPart(true).Cast(); if (view) { ViewSite::Pointer site = view->GetSite().Cast(); pres->ReplacePlaceholderWithPart(site->GetPane().Cast()); } } else { pres->ReplacePlaceholderWithPart(ref->GetPane()); } } // // Load the fast views // if (fastViewManager != 0) // fastViewManager.restoreState(memento, result); // Load the view layout recs QList recMementos(memento ->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); for (int i = 0; i < recMementos.size(); i++) { IMemento::Pointer recMemento = recMementos[i]; QString compoundId; if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId)) { ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true); QString closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr); if (WorkbenchConstants::FALSE_VAL == closeablestr) { rec->isCloseable = false; } QString moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr); if (WorkbenchConstants::FALSE_VAL == moveablestr) { rec->isMoveable = false; } QString standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr); if (WorkbenchConstants::TRUE_VAL == standalonestr) { rec->isStandalone = true; QString showstr; recMemento->GetString(WorkbenchConstants::TAG_SHOW_TITLE, showstr); rec->showTitle = WorkbenchConstants::FALSE_VAL != showstr; } } } //final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); try { // one big try block, don't kill me here // // defer context events // if (service != 0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // // HashSet knownActionSetIds = new HashSet(); // // // Load the always on action sets. QList actions; // = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // // knownActionSetIds.add(actionSetID); // } // } // // // Load the always off action sets. // actions = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOff(d); // } // }); // knownActionSetIds.add(actionSetID); // } // } // Load "show view actions". actions = memento->GetChildren(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); showViewShortcuts.push_back(id); } // // Load "show in times". // actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // String timeStr = actions[x] // .getString(IWorkbenchConstants.TAG_TIME); // if (id != 0 && timeStr != 0) // { // try // { // long time = Long.parseLong(timeStr); // showInTimes.put(id, new Long(time)); // } // catch (NumberFormatException e) // { // // skip this one // } // } // } // Load "show in parts" from registry, not memento showInPartIds = this->GetShowInIdsFromRegistry(); // // Load "new wizard actions". // actions = memento // .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // newWizardShortcuts = new ArrayList(actions.length); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // newWizardShortcuts.add(id); // } // Load "perspective actions". actions = memento->GetChildren(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); perspectiveShortcuts.push_back(id); } // ArrayList extActionSets = getPerspectiveExtensionActionSets(); // for (int i = 0; i < extActionSets.size(); i++) // { // String actionSetID = (String) extActionSets.get(i); // if (knownActionSetIds.contains(actionSetID)) // { // continue; // } // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // knownActionSetIds.add(d.getId()); // } // } // // Add the visible set of action sets to our knownActionSetIds // // Now go through the registry to ensure we pick up any new action // // sets // // that have been added but not yet considered by this perspective. // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // IActionSetDescriptor[] array = reg.getActionSets(); // int count = array.length; // for (int i = 0; i < count; i++) // { // IActionSetDescriptor desc = array[i]; // if ((!knownActionSetIds.contains(desc.getId())) // && (desc.isInitiallyVisible())) // { // addActionSet(desc); // } // } } catch (...) { // // restart context changes // if (service != 0) // { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // }); // } } // Save presentation. presentation = pres; // Hide the editor area if needed. Need to wait for the // presentation to be fully setup first. int areaVisible = 0; bool areaVisibleExists = memento->GetInteger(WorkbenchConstants::TAG_AREA_VISIBLE, areaVisible); // Rather than hiding the editors now we must wait until after their // controls // are created. This ensures that if an editor is instantiated, // createPartControl // is also called. See bug 20166. shouldHideEditorsOnActivate = (areaVisibleExists && areaVisible == 0); // // Restore the trim state of the editor area // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // Integer trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE); // if (trimStateInt != 0) // { // editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state // editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0; // } // } // restore the fixed state int isFixed = 0; fixed = (memento->GetInteger(WorkbenchConstants::TAG_FIXED, isFixed) && isFixed == 1); return true; } QList Perspective::GetShowInIdsFromRegistry() { PerspectiveExtensionReader reader; QList tags; tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART); reader.SetIncludeOnlyTags(tags); PageLayout::Pointer layout(new PageLayout()); reader.ExtendLayout(descriptor->GetOriginalId(), layout); return layout->GetShowInPartIds(); } void Perspective::SaveDesc() { this->SaveDescAs(descriptor); } void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer /*desc*/) { //TODO Perspective SaveDescAs // PerspectiveDescriptor::Pointer realDesc = desc.Cast(); // //get the layout from the registry // PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin // ::GetDefault()->GetPerspectiveRegistry()); // // Capture the layout state. // XMLMemento memento = XMLMemento.createWriteRoot("perspective");//$NON-NLS-1$ // IStatus status = saveState(memento, realDesc, false); // if (status.getSeverity() == IStatus.ERR) // { // ErrorDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage, // status); // return; // } // //save it to the preference store // try // { // perspRegistry.saveCustomPersp(realDesc, memento); // descriptor = realDesc; // } // catch (IOException e) // { // perspRegistry.deletePerspective(realDesc); // MessageDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage); // } } bool Perspective::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); // // result.merge(saveState(memento, descriptor, true)); bool result = true; result &= this->SaveState(memento, descriptor, true); return result; } bool Perspective::SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); bool result = true; if (this->memento) { memento->PutMemento(this->memento); return result; } // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING); //result.add(p.saveState(memento)); result &= p->SaveState(memento); if (!saveInnerViewState) { - Rectangle bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds()); + QRect bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds()); IMemento::Pointer boundsMem = memento ->CreateChild(WorkbenchConstants::TAG_WINDOW); - boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x); - boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); - boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); - boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); + boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x()); + boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y()); + boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height()); + boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width()); } // // Save the "always on" action sets. // Iterator itr = alwaysOnActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // // Save the "always off" action sets. // itr = alwaysOffActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // Save "show view actions" for (QList::iterator itr = showViewShortcuts.begin(); itr != showViewShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // // Save "show in times" // itr = showInTimes.keySet().iterator(); // while (itr.hasNext()) // { // String id = (String) itr.next(); // Long time = (Long) showInTimes.get(id); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME); // child.putString(IWorkbenchConstants.TAG_ID, id); // child.putString(IWorkbenchConstants.TAG_TIME, time.toString()); // } // // Save "new wizard actions". // itr = newWizardShortcuts.iterator(); // while (itr.hasNext()) // { // String str = (String) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // child.putString(IWorkbenchConstants.TAG_ID, str); // } // Save "perspective actions". for (QList::iterator itr = perspectiveShortcuts.begin(); itr != perspectiveShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // Get visible views. QList viewPanes; presentation->CollectViewPanes(viewPanes); // Save the views. for (QList::iterator itr = viewPanes.begin(); itr != viewPanes.end(); ++itr) { IWorkbenchPartReference::Pointer ref((*itr)->GetPartReference()); IViewDescriptor::Pointer desc = page->GetViewFactory()->GetViewRegistry() ->Find(ref->GetId()); if(desc && desc->IsRestorable()) { IMemento::Pointer viewMemento = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref.Cast())); } } // // save all fastview state // if (fastViewManager != 0) // fastViewManager.saveState(memento); // Save the view layout recs. for (QHash::iterator i = mapIDtoViewLayoutRec.begin(); i != mapIDtoViewLayoutRec.end(); ++i) { QString compoundId(i.key()); ViewLayoutRec::Pointer rec(i.value()); if (rec && (!rec->isCloseable || !rec->isMoveable || rec->isStandalone)) { IMemento::Pointer layoutMemento(memento ->CreateChild(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); layoutMemento->PutString(WorkbenchConstants::TAG_ID, compoundId); if (!rec->isCloseable) { layoutMemento->PutString(WorkbenchConstants::TAG_CLOSEABLE, WorkbenchConstants::FALSE_VAL); } if (!rec->isMoveable) { layoutMemento->PutString(WorkbenchConstants::TAG_MOVEABLE, WorkbenchConstants::FALSE_VAL); } if (rec->isStandalone) { layoutMemento->PutString(WorkbenchConstants::TAG_STANDALONE, WorkbenchConstants::TRUE_VAL); layoutMemento->PutString(WorkbenchConstants::TAG_SHOW_TITLE, rec->showTitle ? WorkbenchConstants::TRUE_VAL : WorkbenchConstants::FALSE_VAL); } } } // Save the layout. IMemento::Pointer childMem(memento->CreateChild(WorkbenchConstants::TAG_LAYOUT)); //result.add(presentation.saveState(childMem)); result &= presentation->SaveState(childMem); // Save the editor visibility state if (this->IsEditorAreaVisible()) { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 0); } // // Save the trim state of the editor area if using the new min/max // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // int trimState = editorAreaState; // trimState |= editorAreaRestoreOnUnzoom ? 4 : 0; // memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState); // } // Save the fixed state if (fixed) { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 0); } return result; } void Perspective::SetPerspectiveActionIds(const QList& list) { perspectiveShortcuts = list; } void Perspective::SetShowInPartIds(const QList& list) { showInPartIds = list; } void Perspective::SetShowViewActionIds(const QList& list) { showViewShortcuts = list; } void Perspective::ShowEditorArea() { if (this->IsEditorAreaVisible()) { return; } editorHidden = false; // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) { // If the editor area is going to show then we have to restore // if (getPresentation().getMaximizedStack() != 0) // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); this->ShowEditorAreaLocal(); } // else // setEditorAreaTrimVisibility(true); } else { this->ShowEditorAreaLocal(); } } void Perspective::ShowEditorAreaLocal() { if (editorHolder == 0 || editorHidden) { return; } // Replace the part holder with the editor area. presentation->GetLayout()->Replace(editorHolder, editorArea); editorHolder = 0; } void Perspective::SetEditorAreaState(int newState) { if (newState == editorAreaState) return; editorAreaState = newState; // // reset the restore flag if we're not minimized // if (newState != IStackPresentationSite::STATE_MINIMIZED) // editorAreaRestoreOnUnzoom = false; this->RefreshEditorAreaVisibility(); } int Perspective::GetEditorAreaState() { return editorAreaState; } void Perspective::RefreshEditorAreaVisibility() { // Nothing shows up if the editor area isn't visible at all if (editorHidden) { this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(false); return; } PartStack::Pointer editorStack = editorArea.Cast()->GetUpperRightEditorStack(); if (editorStack == 0) return; // Whatever we're doing, make the current editor stack match it //editorStack->SetStateLocal(editorAreaState); // If it's minimized then it's in the trim if (editorAreaState == IStackPresentationSite::STATE_MINIMIZED) { // Hide the editor area and show its trim this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(true); } else { // Show the editor area and hide its trim //setEditorAreaTrimVisibility(false); this->ShowEditorAreaLocal(); // if (editorAreaState == IStackPresentationSite::STATE_MAXIMIZED) // getPresentation().setMaximizedStack(editorStack); } } IViewReference::Pointer Perspective::GetViewReference(const QString& viewId, const QString& secondaryId) { IViewReference::Pointer ref = page->FindViewReference(viewId, secondaryId); if (ref == 0) { ViewFactory* factory = this->GetViewFactory(); try { ref = factory->CreateView(viewId, secondaryId); } catch (PartInitException& /*e*/) { // IStatus status = StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e); // StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$ // StatusManager.LOG); //TODO Perspective status message WorkbenchPlugin::Log("Failed to create view: id=" + viewId); } } return ref; } IViewPart::Pointer Perspective::ShowView(const QString& viewId, const QString& secondaryId) { ViewFactory* factory = this->GetViewFactory(); IViewReference::Pointer ref = factory->CreateView(viewId, secondaryId); IViewPart::Pointer part = ref->GetPart(true).Cast(); if (part == 0) { throw PartInitException("Could not create view: " + ref->GetId()); } PartSite::Pointer site = part->GetSite().Cast(); PartPane::Pointer pane = site->GetPane(); //TODO Perspective preference store // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE); // // if (openViewMode == IPreferenceConstants.OVM_FAST && // fastViewManager != 0) // { // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true); // setActiveFastView(ref); // } // else if (openViewMode == IPreferenceConstants.OVM_FLOAT // && presentation.canDetach()) // { // presentation.addDetachedPart(pane); // } // else // { if (this->UseNewMinMax(Perspective::Pointer(this))) { // Is this view going to show in the trim? // LayoutPart vPart = presentation.findPart(viewId, secondaryId); // Determine if there is a trim stack that should get the view QString trimId; // // If we can locate the correct trim stack then do so // if (vPart != 0) // { // String id = 0; // ILayoutContainer container = vPart.getContainer(); // if (container.Cast() != 0) // id = ((ContainerPlaceholder)container).getID(); // else if (container.Cast() != 0) // id = ((ViewStack)container).getID(); // // // Is this place-holder in the trim? // if (id != 0 && fastViewManager.getFastViews(id).size()> 0) // { // trimId = id; // } // } // // // No explicit trim found; If we're maximized then we either have to find an // // arbitrary stack... // if (trimId == 0 && presentation.getMaximizedStack() != 0) // { // if (vPart == 0) // { // ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack(); // if (blTrimStack != 0) // { // // OK, we've found a trim stack to add it to... // trimId = blTrimStack.getId(); // // // Since there was no placeholder we have to add one // LayoutPart blPart = presentation.findPart(trimId, 0); // if (blPart.Cast() != 0) // { // ContainerPlaceholder cph = (ContainerPlaceholder) blPart; // if (cph.getRealContainer().Cast() != 0) // { // ViewStack vs = (ViewStack) cph.getRealContainer(); // // // Create a 'compound' id if this is a multi-instance part // String compoundId = ref.getId(); // if (ref.getSecondaryId() != 0) // compoundId = compoundId + ':' + ref.getSecondaryId(); // // // Add the new placeholder // vs.add(new PartPlaceholder(compoundId)); // } // } // } // } // } // // // If we have a trim stack located then add the view to it // if (trimId != "") // { // fastViewManager.addViewReference(trimId, -1, ref, true); // } // else // { // bool inMaximizedStack = vPart != 0 && vPart.getContainer() == presentation.getMaximizedStack(); // Do the default behavior presentation->AddPart(pane); // // Now, if we're maximized then we have to minimize the new stack // if (presentation.getMaximizedStack() != 0 && !inMaximizedStack) // { // vPart = presentation.findPart(viewId, secondaryId); // if (vPart != 0 && vPart.getContainer().Cast() != 0) // { // ViewStack vs = (ViewStack)vPart.getContainer(); // vs.setState(IStackPresentationSite.STATE_MINIMIZED); // // // setting the state to minimized will create the trim toolbar // // so we don't need a 0 pointer check here... // fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true); // } // } // } } else { presentation->AddPart(pane); } //} // Ensure that the newly showing part is enabled if (pane != 0 && pane->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(pane->GetControl(), true); return part; } IWorkbenchPartReference::Pointer Perspective::GetOldPartRef() { return oldPartRef; } void Perspective::SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef) { this->oldPartRef = oldPartRef; } bool Perspective::IsCloseable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isCloseable; } return true; } bool Perspective::IsMoveable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isMoveable; } return true; } void Perspective::DescribeLayout(QString& buf) const { // QList fastViews = getFastViews(); // // if (fastViews.length != 0) // { // buf.append("fastviews ("); //$NON-NLS-1$ // for (int idx = 0; idx < fastViews.length; idx++) // { // IViewReference ref = fastViews[idx]; // // if (idx> 0) // { // buf.append(", "); //$NON-NLS-1$ // } // // buf.append(ref.getPartName()); // } // buf.append("), "); //$NON-NLS-1$ // } this->GetPresentation()->DescribeLayout(buf); } void Perspective::TestInvariants() { this->GetPresentation()->GetLayout()->TestInvariants(); } bool Perspective::UseNewMinMax(Perspective::Pointer activePerspective) { // We need to have an active perspective if (activePerspective == 0) return false; // We need to have a trim manager (if we don't then we // don't create a FastViewManager because it'd be useless) // if (activePerspective->GetFastViewManager() == 0) // return false; // Make sure we don't NPE anyplace WorkbenchWindow::Pointer wbw = activePerspective->page->GetWorkbenchWindow().Cast(); if (wbw == 0) return false; // WorkbenchWindowConfigurer* configurer = wbw->GetWindowConfigurer(); // if (configurer == 0) // return false; IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); if (factory == 0) return false; // Ok, we should be good to go, return the pref //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp index d3f696e88a..e2e24142b2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp @@ -1,1492 +1,1492 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryEditorSashContainer.h" #include "berryDragUtil.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchConstants.h" #include namespace berry { const int PerspectiveHelper::MIN_DETACH_WIDTH = 150; const int PerspectiveHelper::MIN_DETACH_HEIGHT = 250; PerspectiveHelper::DragOverListener::DragOverListener(PerspectiveHelper* perspHelper) : perspHelper(perspHelper) { } IDropTarget::Pointer PerspectiveHelper::DragOverListener::Drag( - void* /*currentControl*/, const Object::Pointer& draggedObject, const Point& /*position*/, - const Rectangle& dragRectangle) + void* /*currentControl*/, const Object::Pointer& draggedObject, const QPoint& /*position*/, + const QRect& dragRectangle) { if (draggedObject.Cast() != 0) { PartPane::Pointer part = draggedObject.Cast(); if (part->GetContainer().Cast()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); // Views that haven't been shown yet have no 'control' which causes // 'GetWorkbenchWindow' to return 'null' so check explicitly if (part->GetPage() != perspHelper->page) return IDropTarget::Pointer(0); else if (part->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, part, dragRectangle); else perspHelper->dropTarget->SetTarget(part, dragRectangle); } else if (draggedObject.Cast() != 0) { PartStack::Pointer stack = draggedObject.Cast(); if (stack->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); if (stack->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, stack, dragRectangle); else perspHelper->dropTarget->SetTarget(stack, dragRectangle); } return perspHelper->dropTarget; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartPane::Pointer part, - const Rectangle& dragRectangle) + const QRect& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, - const Rectangle& dragRectangle) + const QRect& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, - const Rectangle& dragRectangle) + const QRect& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, - const Rectangle& dragRectangle) + const QRect& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(stack, dragRectangle); } void PerspectiveHelper::ActualDropTarget::Drop() { if (part != 0) { Shell::Pointer shell = part->GetShell(); if (shell->GetData().Cast () != 0) { // if only one view in tab folder then do a window move ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { if (container.Cast()->GetItemCount() == 1) { - shell->SetLocation(dragRectangle.x, dragRectangle.y); + shell->SetLocation(dragRectangle.x(), dragRectangle.y()); return; } } } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach - perspHelper->DetachPart(part, dragRectangle.x, dragRectangle.y); + perspHelper->DetachPart(part, dragRectangle.x(), dragRectangle.y()); } else if (stack != 0) { Shell::Pointer shell = stack->GetShell(); if (shell->GetData().Cast () != 0) { // only one tab folder in a detach window, so do window // move - shell->SetLocation(dragRectangle.x, dragRectangle.y); + shell->SetLocation(dragRectangle.x(), dragRectangle.y()); return; } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach - perspHelper->Detach(stack, dragRectangle.x, dragRectangle.y); + perspHelper->Detach(stack, dragRectangle.x(), dragRectangle.y()); } } -DnDTweaklet::CursorType PerspectiveHelper::ActualDropTarget::GetCursor() +CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { - return DnDTweaklet::CURSOR_OFFSCREEN; + return CURSOR_OFFSCREEN; } PerspectiveHelper::MatchingPart::MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part) { this->pid = pid; this->sid = sid; this->part = part; this->len = pid.size() + sid.size(); this->hasWildcard = (pid.indexOf(PartPlaceholder::WILD_CARD) != -1) || (sid.indexOf(PartPlaceholder::WILD_CARD) != -1); } bool PerspectiveHelper::CompareMatchingParts::operator()(const MatchingPart& m1, const MatchingPart& m2) const { // specific ids always outweigh ids with wildcards if (m1.hasWildcard && !m2.hasWildcard) { return true; } if (!m1.hasWildcard && m2.hasWildcard) { return false; } // if both are specific or both have wildcards, simply compare based on length return m1.len > m2.len; } PerspectiveHelper::PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* persp) : page(workbenchPage), perspective(persp), mainLayout(mainLayout), detachable(false), active(false) { // Views can be detached if the feature is enabled (true by default, // use the plug-in customization file to disable), and if the platform // supports detaching. this->dragTarget.reset(new DragOverListener(this)); //TODO preference store // IPreferenceStore store = PlatformUI.getPreferenceStore(); // this.detachable = store.getBoolean( // IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS); this->detachable = true; if (this->detachable) { // Check if some arbitrary Composite supports reparenting. If it // doesn't, views cannot be detached. void* client = workbenchPage->GetClientComposite(); if (client == 0) { // The workbench page is not initialized. I don't think this can happen, // but if it does, silently set detachable to false. this->detachable = false; } else { this->detachable = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsReparentable(client); } } } void PerspectiveHelper::Activate(void* parent) { if (active) { return; } parentWidget = parent; // Activate main layout // make sure all the views have been properly parented QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { PartPane::Pointer part = *iter; part->Reparent(parent); } mainLayout->CreateControl(parent); mainLayout->SetActive(true); // Open the detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Open(); } this->EnableAllDrag(); // // Ensure that the maximized stack's presentation state is correct // if (maximizedStackId != 0) // { // LayoutPart part = this->FindPart(maximizedStackId); // if (part.Cast() != 0) // { // maximizedStack = (PartStack) part; // maximizedStackId = 0; // } // } // // // NOTE: we only handle ViewStacks here; Editor Stacks are handled by the // // perspective // if (maximizedStack instanceof ViewStack) // { // maximizedStack.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } active = true; } void PerspectiveHelper::AddPart(LayoutPart::Pointer part) { // Look for a placeholder. PartPlaceholder::Pointer placeholder; LayoutPart::Pointer testPart; QString primaryId = part->GetID(); QString secondaryId; IViewReference::Pointer ref; if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast (); ref = pane->GetPartReference().Cast (); if (ref != 0) secondaryId = ref->GetSecondaryId(); } if (secondaryId != "") { testPart = this->FindPart(primaryId, secondaryId); } else { testPart = this->FindPart(primaryId); } // validate the testPart if (testPart != 0 && testPart.Cast() != 0) { placeholder = testPart.Cast (); } // If there is no placeholder do a simple add. Otherwise, replace the // placeholder if its not a pattern matching placholder if (placeholder == 0) { part->Reparent(mainLayout->GetParent()); LayoutPart::Pointer relative = mainLayout->FindBottomRight(); if (relative != 0 && relative.Cast() != 0) { ILayoutContainer::Pointer stack = relative.Cast (); if (stack->AllowsAdd(part)) { mainLayout->Stack(part, stack); } else { mainLayout->AddPart(part); } } else { mainLayout->AddPart(part); } } else { ILayoutContainer::Pointer container = placeholder->GetContainer(); if (container != 0) { if (container.Cast () != 0) { //Create a detached window add the part on it. DetachedPlaceHolder::Pointer holder = container.Cast(); detachedPlaceHolderList.removeAll(holder); container->Remove(testPart); DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); part->CreateControl(window->GetShell()->GetControl()); // Open window. window->GetShell()->SetBounds(holder->GetBounds()); window->Open(); // add part to detached window. PartPane::Pointer pane = part.Cast(); window->Add(pane); QList otherChildren = holder->GetChildren(); for (QList::iterator iter = otherChildren.begin(); iter != otherChildren.end(); ++iter) { part->GetContainer()->Add(*iter); } } else { // show parent if necessary if (container.Cast () != 0) { ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); if (parentContainer == 0) return; container = containerPlaceholder->GetRealContainer().Cast(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } // // reparent part. // if (container.Cast() == 0) // { // // We don't need to reparent children of PartTabFolders since they will automatically // // reparent their children when they become visible. This if statement used to be // // part of an else branch. Investigate if it is still necessary. // part->Reparent(mainLayout->GetParent()); // } // see if we should replace the placeholder if (placeholder->HasWildCard()) { if (PartSashContainer::Pointer sashContainer = container.Cast()) { sashContainer->AddChildForPlaceholder(part, placeholder); } else { container->Add(part); } } else { container->Replace(placeholder, part); } } } } } void PerspectiveHelper::AttachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); // Restore any maximized part before re-attaching. // Note that 'getMaximizedStack != 0' implies 'useNewMinMax' // if (getMaximizedStack() != 0) // { // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } this->DerefPart(pane); this->AddPart(pane); this->BringPartToTop(pane); pane->SetFocus(); } bool PerspectiveHelper::CanDetach() { return detachable; } bool PerspectiveHelper::BringPartToTop(LayoutPart::Pointer part) { ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); if (folder->GetSelection() != part) { folder->SetSelection(part); return true; } } return false; } bool PerspectiveHelper::IsPartVisible(IWorkbenchPartReference::Pointer partRef) { LayoutPart::Pointer foundPart; if (partRef.Cast () != 0) { foundPart = this->FindPart(partRef->GetId(), partRef.Cast()->GetSecondaryId()); } else { foundPart = this->FindPart(partRef->GetId()); } if (foundPart == 0) { return false; } if (foundPart.Cast () != 0) { return false; } ILayoutContainer::Pointer container = foundPart->GetContainer(); if (container.Cast () != 0) { return false; } if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); LayoutPart::Pointer visiblePart = folder->GetSelection(); if (visiblePart == 0) { return false; } return partRef == visiblePart.Cast()->GetPartReference(); } return true; } bool PerspectiveHelper::WillPartBeVisible(const QString& partId) { return this->WillPartBeVisible(partId, 0); } bool PerspectiveHelper::WillPartBeVisible(const QString& partId, const QString& secondaryId) { LayoutPart::Pointer part = this->FindPart(partId, secondaryId); if (part == 0) { return false; } ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { container = container.Cast()->GetRealContainer().Cast(); } if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); if (folder->GetSelection() == 0) { return false; } return part->GetID() == folder->GetSelection()->GetID(); } return true; } QList PerspectiveHelper::CollectPlaceholders() { // Scan the main window. QList results = this->CollectPlaceholders( mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; QList moreResults = win->GetChildren(); if (moreResults.size()> 0) { for (QList::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) results.push_back(iter->Cast()); } } } } return results; } QList PerspectiveHelper::CollectPlaceholders( const QList& parts) { QList result; for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (ILayoutContainer::Pointer container = part.Cast()) { // iterate through sub containers to find sub-parts QList newParts = this->CollectPlaceholders( container->GetChildren()); result.append(newParts); } else if (PartPlaceholder::Pointer placeholder = part.Cast()) { result.push_back(placeholder); } } return result; } void PerspectiveHelper::CollectViewPanes(QList& result) { // Scan the main window. this->CollectViewPanes(result, mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; CollectViewPanes(result, win->GetChildren()); } } } void PerspectiveHelper::CollectViewPanes(QList& result, const QList& parts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (PartPane::Pointer partPane = part.Cast()) { if(partPane->GetPartReference().Cast()) { result.push_back(partPane); } } else if (ILayoutContainer::Pointer container = part.Cast ()) { this->CollectViewPanes(result, container->GetChildren()); } } } void PerspectiveHelper::Deactivate() { if (!active) { return; } this->DisableAllDrag(); // Reparent all views to the main window void* parent = mainLayout->GetParent(); QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer window = *winIter; CollectViewPanes(children, window->GetChildren()); } // *** Do we even need to do this if detached windows not supported? for (QList::iterator itr = children.begin(); itr != children.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } // Dispose main layout. mainLayout->SetActive(false); // Dispose the detached windows for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Close(); } active = false; } PerspectiveHelper::~PerspectiveHelper() { mainLayout->Dispose(); mainLayout->DisposeSashes(); } void PerspectiveHelper::DescribeLayout(QString& buf) const { if (detachable) { if (detachedWindowList.size() != 0) { buf.append("detachedWindows ("); //$NON-NLS-1$ for (DetachedWindowsType::const_iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::ConstPointer window = *winIter; QList children = window->GetChildren(); int j = 0; if (children.size() != 0) { buf.append("dWindow ("); //$NON-NLS-1$ for (QList::iterator partIter = children.begin(); partIter != children.end(); ++partIter, ++j) { if (partIter->Cast() != 0) buf.append(partIter->Cast()->GetPlaceHolderId()); else if (partIter->Cast() != 0) buf.append( partIter->Cast()->GetPartReference()->GetPartName()); if (j < (children.size() - 1)) { buf.append(", "); //$NON-NLS-1$ } } buf.append(")"); //$NON-NLS-1$ } } buf.append("), "); //$NON-NLS-1$ } } this->GetLayout()->DescribeLayout(buf); } void PerspectiveHelper::DerefPart(LayoutPart::Pointer part) { // if (part.Cast () != 0) // { // IViewReference::Pointer ref = ((ViewPane) part).getViewReference(); // if (perspective.isFastView(ref)) // { // // Special check: if it's a fast view then it's actual ViewStack // // may only contain placeholders and the stack is represented in // // the presentation by a container placeholder...make sure the // // PartPlaceHolder for 'ref' is removed from the ViewStack // String id = perspective.getFastViewManager().getIdForRef(ref); // LayoutPart parentPart = findPart(id, 0); // if (parentPart.Cast () != 0) // { // ViewStack vs = // (ViewStack) ((ContainerPlaceholder) parentPart).getRealContainer(); // QList kids = vs.getChildren(); // for (int i = 0; i < kids.length; i++) // { // if (kids[i].Cast () != 0) // { // if (ref.getId().equals(kids[i].id)) // vs.remove(kids[i]); // } // } // } // perspective.getFastViewManager().removeViewReference(ref, true, true); // } // } // Get vital part stats before reparenting. ILayoutContainer::Pointer oldContainer = part->GetContainer(); bool wasDocked = part->IsDocked(); Shell::Pointer oldShell = part->GetShell(); // Reparent the part back to the main window part->Reparent(mainLayout->GetParent()); // Update container. if (oldContainer == 0) { return; } oldContainer->Remove(part); ILayoutContainer::ChildrenType children = oldContainer->GetChildren(); if (wasDocked) { bool hasChildren = (children.size()> 0); if (hasChildren) { // make sure one is at least visible int childVisible = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if ((*iter)->GetControl() != 0) { childVisible++; } } // none visible, then reprarent and remove container if (oldContainer.Cast () != 0) { PartStack::Pointer folder = oldContainer.Cast(); // Is the part in the trim? bool inTrim = false; // // Safety check...there may be no FastViewManager // if (perspective.getFastViewManager() != 0) // inTrim // = perspective.getFastViewManager().getFastViews(folder.getID()).size() // > 0; if (childVisible == 0 && !inTrim) { ILayoutContainer::Pointer parentContainer = folder->GetContainer(); hasChildren = folder->GetChildren().size()> 0; // We maintain the stack as a place-holder if it has children // (which at this point would represent view place-holders) if (hasChildren) { folder->Dispose(); // replace the real container with a ContainerPlaceholder ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(folder->GetID())); placeholder->SetRealContainer(folder); parentContainer->Replace(folder, placeholder); } } else if (childVisible == 1) { LayoutTree::Pointer layout = mainLayout->GetLayoutTree(); layout = layout->Find(folder); layout->SetBounds(layout->GetBounds()); } } } if (!hasChildren) { // There are no more children in this container, so get rid of // it if (oldContainer.Cast () != 0) { //BERRY_INFO << "No children left, removing container\n"; LayoutPart::Pointer parent = oldContainer.Cast(); ILayoutContainer::Pointer parentContainer = parent->GetContainer(); if (parentContainer != 0) { parentContainer->Remove(parent); parent->Print(qDebug()); parent->Dispose(); } } } } else if (!wasDocked) { if (children.empty()) { // There are no more children in this container, so get rid of // it // Turn on redraw again just in case it was off. //oldShell.setRedraw(true); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } else { // There are children. If none are visible hide detached // window. bool allInvisible = true; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible) { DetachedPlaceHolder::Pointer placeholder(new DetachedPlaceHolder("", oldShell->GetBounds())); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { oldContainer->Remove(*iter); (*iter)->SetContainer(placeholder); placeholder->Add(*iter); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. - Point size = part->GetSize(); - if (size.x == 0 || size.y == 0) + QSize size = part->GetSize(); + if (size.width() == 0 || size.height() == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } - int width = std::max(size.x, MIN_DETACH_WIDTH); - int height = std::max(size.y, MIN_DETACH_HEIGHT); + int width = std::max(size.width(), MIN_DETACH_WIDTH); + int height = std::max(size.height(), MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); if (part.Cast () != 0) { //window.getShell().setRedraw(false); //parentWidget.setRedraw(false); PartStack::Pointer stack = part.Cast(); LayoutPart::Pointer visiblePart = stack->GetSelection(); ILayoutContainer::ChildrenType children = stack->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (PartPane::Pointer partPane = iter->Cast() // && check it is a view? ) { // remove the part from its current container this->DerefPart(*iter); // add part to detached window. window->Add(*iter); } } if (visiblePart != 0) { this->BringPartToTop(visiblePart); visiblePart->SetFocus(); } //window.getShell().setRedraw(true); //parentWidget.setRedraw(true); } } void PerspectiveHelper::DetachPart(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. - Point size = part->GetSize(); - if (size.x == 0 || size.y == 0) + QSize size = part->GetSize(); + if (size.width() == 0 || size.height() == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } - int width = std::max(size.x, MIN_DETACH_WIDTH); - int height = std::max(size.y, MIN_DETACH_HEIGHT); + int width = std::max(size.width(), MIN_DETACH_WIDTH); + int height = std::max(size.height(), MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); // remove the part from its current container this->DerefPart(part); // add part to detached window. window->Add(part); part->SetFocus(); } void PerspectiveHelper::DetachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); if (this->CanDetach() && pane != 0) { // if (getMaximizedStack() != 0) // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); - Rectangle bounds = pane->GetParentBounds(); - this->DetachPart(pane, bounds.x, bounds.y); + QRect bounds = pane->GetParentBounds(); + this->DetachPart(pane, bounds.x(), bounds.y()); } } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part) { // Calculate detached window size. - Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); - bounds.x = bounds.x + (bounds.width - 300) / 2; - bounds.y = bounds.y + (bounds.height - 300) / 2; + QRect bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); + bounds.setX(bounds.x() + (bounds.width() - 300) / 2); + bounds.setY(bounds.y() + (bounds.height() - 300) / 2); this->AddDetachedPart(part, bounds); } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part, - const Rectangle& bounds) + const QRect& bounds) { // Detaching is disabled on some platforms .. if (!detachable) { this->AddPart(part); return; } // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); // add part to detached window. part->CreateControl(window->GetShell()->GetControl()); window->Add(part); // Open window. - window->GetShell()->SetBounds(bounds.x, bounds.y, bounds.width, bounds.height); + window->GetShell()->SetBounds(bounds.x(), bounds.y(), bounds.width(), bounds.height()); window->Open(); part->SetFocus(); } void PerspectiveHelper::DisableAllDrag() { DragUtil::RemoveDragTarget(0, dragTarget.data()); } void PerspectiveHelper::EnableAllDrag() { DragUtil::AddDragTarget(0, dragTarget.data()); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id) { return this->FindPart(id, ""); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId) { //BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl; // check main window. QList matchingParts; LayoutPart::Pointer part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, mainLayout->GetChildren(), matchingParts) : this->FindPart(primaryId, mainLayout->GetChildren(), matchingParts); if (part != 0) { return part; } // check each detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { DetachedWindow::Pointer window = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, window->GetChildren(), matchingParts) : this->FindPart(primaryId, window->GetChildren(), matchingParts); if (part != 0) { return part; } } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { DetachedPlaceHolder::Pointer holder = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, holder->GetChildren(), matchingParts) : this->FindPart(primaryId, holder->GetChildren(), matchingParts); if (part != 0) { return part; } } //BERRY_INFO << "Looking through the matched parts (count: " << matchingParts.size() << ")\n"; // sort the matching parts if (matchingParts.size()> 0) { std::partial_sort(matchingParts.begin(), (matchingParts.begin()), matchingParts.end(), CompareMatchingParts()); const MatchingPart& mostSignificantPart = matchingParts.front(); return mostSignificantPart.part; } // Not found. return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check for part equality, parts with secondary ids fail if (part->GetID() == id) { if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetSecondaryId() != "") { continue; } } return part; } // check pattern matching placeholders else if (part->IsPlaceHolder() && part.Cast()->HasWildCard()) { QRegExp re(id, Qt::CaseInsensitive); if (re.exactMatch(part->GetID())) { matchingParts.push_back(MatchingPart(part->GetID(), "", part)); } // StringMatcher sm = new StringMatcher(part.getID(), true, false); // if (sm.match(id)) // { // matchingParts .add(new MatchingPart(part.getID(), 0, part)); // } } else if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { part = FindPart(id, layoutContainer->GetChildren(), matchingParts); if (part) { return part; } } } //BERRY_INFO << "Returning 0\n"; return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check containers first if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { LayoutPart::Pointer testPart = FindPart(primaryId, secondaryId, layoutContainer->GetChildren(), matchingParts); if (testPart) { return testPart; } } // check for view part equality if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetId() == primaryId && ref->GetSecondaryId() == secondaryId) { return part; } } // check placeholders else if (part.Cast () != 0) { QString id = part->GetID(); // optimization: don't bother parsing id if it has no separator -- it can't match QString phSecondaryId = ViewFactory::ExtractSecondaryId(id); if (phSecondaryId == "") { // but still need to check for wildcard case if (id == PartPlaceholder::WILD_CARD) { matchingParts.push_back(MatchingPart(id, "", part)); } continue; } QString phPrimaryId = ViewFactory::ExtractPrimaryId(id); // perfect matching pair if (phPrimaryId == primaryId && phSecondaryId == secondaryId) { return part; } // check for partial matching pair QRegExp pre(phPrimaryId, Qt::CaseInsensitive); if (pre.exactMatch(primaryId)) { QRegExp sre(phSecondaryId, Qt::CaseInsensitive); if (sre.exactMatch(secondaryId)) { matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part)); } } } } return LayoutPart::Pointer(0); } bool PerspectiveHelper::HasPlaceholder(const QString& id) { return this->HasPlaceholder(id, 0); } bool PerspectiveHelper::HasPlaceholder(const QString& primaryId, const QString& secondaryId) { LayoutPart::Pointer testPart; if (secondaryId == "") { testPart = this->FindPart(primaryId); } else { testPart = this->FindPart(primaryId, secondaryId); } return (testPart != 0 && testPart.Cast () != 0); } PartSashContainer::Pointer PerspectiveHelper::GetLayout() const { return mainLayout; } bool PerspectiveHelper::IsActive() { return active; } float PerspectiveHelper::GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target) { if ((source.Cast () != 0 || source.Cast () != 0) && target.Cast () != 0) { return 0.25f; } return 0.5f; } void PerspectiveHelper::RemovePart(LayoutPart::Pointer part) { // Reparent the part back to the main window void* parent = mainLayout->GetParent(); part->Reparent(parent); // Replace part with a placeholder ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0) { QString placeHolderId = part->GetPlaceHolderId(); container->Replace(part, LayoutPart::Pointer(new PartPlaceholder(placeHolderId))); // // If the parent is root we're done. Do not try to replace // // it with placeholder. // if (container == mainLayout) // { // return; // } // If the parent is empty replace it with a placeholder. QList children = container->GetChildren(); bool allInvisible = true; for (QList::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible && (container.Cast () != 0)) { // what type of window are we in? LayoutPart::Pointer cPart = container.Cast(); //Window oldWindow = cPart.getWindow(); bool wasDocked = cPart->IsDocked(); Shell::Pointer oldShell = cPart->GetShell(); if (wasDocked) { // PR 1GDFVBY: ViewStack not disposed when page // closed. if (container.Cast () != 0) { container.Cast()->Dispose(); } // replace the real container with a // ContainerPlaceholder ILayoutContainer::Pointer parentContainer = cPart->GetContainer(); ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(cPart->GetID())); placeholder->SetRealContainer(container); parentContainer->Replace(cPart, placeholder); } else { DetachedPlaceHolder::Pointer placeholder( new DetachedPlaceHolder("", oldShell->GetBounds())); //$NON-NLS-1$ for (QList::iterator childIter2 = children.begin(); childIter2 != children.end(); ++childIter2) { (*childIter2)->GetContainer()->Remove(*childIter2); (*childIter2)->SetContainer(placeholder); placeholder->Add(*childIter2); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part) { // Look for a PartPlaceholder that will tell us how to position this // object QList placeholders = this->CollectPlaceholders(); for (int i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetID() == part->GetID()) { // found a matching placeholder which we can replace with the // new View ILayoutContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { if (ContainerPlaceholder::Pointer containerPlaceholder = container.Cast ()) { // One of the children is now visible so replace the // ContainerPlaceholder with the real container ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer().Cast(); if (LayoutPart::Pointer layoutPart = container.Cast ()) { parentContainer->Replace(containerPlaceholder, layoutPart); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } container->Replace(placeholders[i], part); return; } } } } bool PerspectiveHelper::RestoreState(IMemento::Pointer memento) { // Restore main window. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->RestoreState(childMem); bool r = mainLayout->RestoreState(childMem); // Restore each floating window. if (detachable) { QList detachedWindows(memento->GetChildren( WorkbenchConstants::TAG_DETACHED_WINDOW)); for (QList::iterator iter = detachedWindows.begin(); iter != detachedWindows.end(); ++iter) { DetachedWindow::Pointer win(new DetachedWindow(page)); detachedWindowList.push_back(win); win->RestoreState(*iter); } QList childrenMem(memento->GetChildren( WorkbenchConstants::TAG_HIDDEN_WINDOW)); for (QList::iterator iter = childrenMem.begin(); iter != childrenMem.end(); ++iter) { DetachedPlaceHolder::Pointer holder( - new DetachedPlaceHolder("", Rectangle(0, 0, 0, 0))); + new DetachedPlaceHolder("", QRect(0, 0, 0, 0))); holder->RestoreState(*iter); detachedPlaceHolderList.push_back(holder); } } // Get the cached id of the currently maximized stack //maximizedStackId = childMem.getString(IWorkbenchConstants.TAG_MAXIMIZED); return r; } bool PerspectiveHelper::SaveState(IMemento::Pointer memento) { // Persist main window. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->SaveState(childMem); bool r = mainLayout->SaveState(childMem); if (detachable) { // Persist each detached window. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_DETACHED_WINDOW); (*iter)->SaveState(childMem); } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_HIDDEN_WINDOW); (*iter)->SaveState(childMem); } } // Write out the id of the maximized (View) stack (if any) // NOTE: we only write this out if it's a ViewStack since the // Editor Area is handled by the perspective // if (maximizedStack.Cast () != 0) // { // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, // maximizedStack.getID()); // } // else if (maximizedStackId != 0) // { // // Maintain the cache if the perspective has never been activated // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, maximizedStackId); // } return r; } void PerspectiveHelper::UpdateBoundsMap() { boundsMap.clear(); // Walk the layout gathering the current bounds of each stack // and the editor area QList kids = mainLayout->GetChildren(); for (QList::iterator iter = kids.begin(); iter != kids.end(); ++iter) { if (iter->Cast () != 0) { PartStack::Pointer vs = iter->Cast(); boundsMap.insert(vs->GetID(), vs->GetBounds()); } else if (iter->Cast () != 0) { EditorSashContainer::Pointer esc = iter->Cast(); boundsMap.insert(esc->GetID(), esc->GetBounds()); } } } void PerspectiveHelper::ResetBoundsMap() { boundsMap.clear(); } -Rectangle PerspectiveHelper::GetCachedBoundsFor(const QString& id) +QRect PerspectiveHelper::GetCachedBoundsFor(const QString& id) { return boundsMap[id]; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h index 8c81cf371e..20996a421c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h @@ -1,573 +1,573 @@ /*=================================================================== 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 BERRYPERSPECTIVEHELPER_H_ #define BERRYPERSPECTIVEHELPER_H_ #include "berryWorkbenchPage.h" #include "berryPartPlaceholder.h" #include "berryPerspective.h" #include "berryViewSashContainer.h" #include "berryPartPlaceholder.h" #include "berryDetachedWindow.h" #include "berryDetachedPlaceHolder.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" #include "berryPartPane.h" namespace berry { class WorkbenchPage; /** * A perspective presentation is a collection of parts with a layout. Each part * is parented to a main window, so you can create more than one presentation * on a set of parts and change the layout just by activating / deactivating a * presentation. * * In addition, the user can change the position of any part by mouse * manipulation (drag & drop). If a part is removed, we leave a placeholder * behind to indicate where it goes should the part be added back. */ class PerspectiveHelper { friend class PartStack; friend class ViewSashContainer; private: WorkbenchPage* page; protected: Perspective* perspective; protected: void* parentWidget; private: ViewSashContainer::Pointer mainLayout; //private: PartStack maximizedStack; /** * If there is a ViewStack maximized on shutdown the id is * cached and restored into this field on 'restoreState'. * This is then used to bash the ViewStack's presentation state * into the correct value on activation (the startup life-cycle * is such that we have to use this 'latch' because the window * state isn't valid until the activate happens. */ //private: String maximizedStackId; private: typedef QList DetachedWindowsType; DetachedWindowsType detachedWindowList; private: typedef QList DetachedPlaceHoldersType; DetachedPlaceHoldersType detachedPlaceHolderList; /** * Maps a stack's id to its current bounds * this is used to capture the current bounds of all * stacks -before- starting a maximize (since the * iterative 'minimize' calls cause the intial stack's * bounds to change. */ private: - QHash boundsMap; + QHash boundsMap; private: bool detachable; protected: bool active; // key is the LayoutPart object, value is the PartDragDrop object //private: IPartDropListener partDropListener; private: static const int MIN_DETACH_WIDTH; private: static const int MIN_DETACH_HEIGHT; struct DragOverListener: public IDragOverListener { DragOverListener(PerspectiveHelper* perspHelper); IDropTarget::Pointer Drag(void* currentControl, - const Object::Pointer& draggedObject, const Point& position, - const Rectangle& dragRectangle); + const Object::Pointer& draggedObject, const QPoint& position, + const QRect& dragRectangle); private: PerspectiveHelper* perspHelper; }; QScopedPointer dragTarget; struct ActualDropTarget: public AbstractDropTarget { berryObjectMacro(ActualDropTarget); /** * @param part * @param dragRectangle * @since 3.1 */ - void SetTarget(PartPane::Pointer part, const Rectangle& dragRectangle); + void SetTarget(PartPane::Pointer part, const QRect& dragRectangle); /** * @param part * @param dragRectangle * @since 3.1 */ - void SetTarget(PartStack::Pointer part, const Rectangle& dragRectangle); + void SetTarget(PartStack::Pointer part, const QRect& dragRectangle); - ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const Rectangle& dragRectangle); + ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle); - ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer part, const Rectangle& dragRectangle); + ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer part, const QRect& dragRectangle); void Drop(); - DnDTweaklet::CursorType GetCursor(); + CursorType GetCursor(); private: PartPane::Pointer part; PartStack::Pointer stack; - Rectangle dragRectangle; + QRect dragRectangle; PerspectiveHelper* perspHelper; }; ActualDropTarget::Pointer dropTarget; private: struct MatchingPart { QString pid; QString sid; LayoutPart::Pointer part; bool hasWildcard; int len; MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part); }; struct CompareMatchingParts: public std::binary_function { bool operator()(const MatchingPart& m1, const MatchingPart& m2) const; }; /** * Constructs a new object. */ public: PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* perspective); /** * Show the presentation. */ public: void Activate(void* parent); /** * Adds a part to the presentation. If a placeholder exists for the part * then swap the part in. Otherwise, add the part in the bottom right * corner of the presentation. */ public: void AddPart(LayoutPart::Pointer part); /** * Attaches a part that was previously detached to the mainLayout. * * @param ref */ public: void AttachPart(IViewReference::Pointer ref); /** * Return whether detachable parts can be supported. */ public: bool CanDetach(); /** * Bring a part forward so it is visible. * * @return true if the part was brought to top, false if not. */ public: bool BringPartToTop(LayoutPart::Pointer part); /** * Returns true if the given part is visible. * A part is visible if it's top-level (not in a tab folder) or if it is the top one * in a tab folder. */ public: bool IsPartVisible(IWorkbenchPartReference::Pointer partRef); /** * Returns true is not in a tab folder or if it is the top one in a tab * folder. */ public: bool WillPartBeVisible(const QString& partId); public: bool WillPartBeVisible(const QString& partId, const QString& secondaryId); /** * Answer a list of the PartPlaceholder objects. */ private: QList CollectPlaceholders(); /** * Answer a list of the PartPlaceholder objects. */ private: QList CollectPlaceholders( const QList& parts); /** * Answer a list of the view panes. */ public: void CollectViewPanes(QList& result); /** * Answer a list of the view panes. */ private: void CollectViewPanes(QList& result, const QList& parts); /** * Hide the presentation. */ public: void Deactivate(); public: ~PerspectiveHelper(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. *

    * This is only intended for use by test suites. *

    * * @param buf */ public: void DescribeLayout(QString& buf) const; /** * Deref a given part. Deconstruct its container as required. Do not remove * drag listeners. */ protected: /* package */void DerefPart(LayoutPart::Pointer part); /** * Create a detached window containing a part. */ private: void DetachPart(LayoutPart::Pointer source, int x, int y); private: void Detach(LayoutPart::Pointer source, int x, int y); /** * Detached a part from the mainLayout. Presently this does not use placeholders * since the current implementation is not robust enough to remember a view's position * in more than one root container. For now the view is simply derefed and will dock * in the default position when attachPart is called. * * By default parts detached this way are set to float on top of the workbench * without docking. It is assumed that people that want to drag a part back onto * the WorkbenchWindow will detach it via drag and drop. * * @param ref */ public: void DetachPart(IViewReference::Pointer ref); /** * Create a detached window containing a part. */ public: void AddDetachedPart(LayoutPart::Pointer part); public: - void AddDetachedPart(LayoutPart::Pointer part, const Rectangle& bounds); + void AddDetachedPart(LayoutPart::Pointer part, const QRect& bounds); /** * disableDragging. */ private: void DisableAllDrag(); /** * enableDragging. */ private: void EnableAllDrag(); /** * Find the first part with a given ID in the presentation. * Wild cards now supported. */ private: LayoutPart::Pointer FindPart(const QString& id); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ public: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId); /** * Find the first part with a given ID in the presentation. */ private: LayoutPart::Pointer FindPart(const QString& id, const QList& parts, QList& matchingParts); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ private: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts); /** * Returns true if a placeholder exists for a given ID. */ public: bool HasPlaceholder(const QString& id); /** * Returns true if a placeholder exists for a given ID. * @since 3.0 */ public: bool HasPlaceholder(const QString& primaryId, const QString& secondaryId); /** * Returns the layout container. */ public: PartSashContainer::Pointer GetLayout() const; /** * Gets the active state. */ public: bool IsActive(); /** * Returns whether the presentation is zoomed. * * NOTE: As of 3.3 this method should always return 'false' * when using the new min/max behavior. It is only used for * legacy 'zoom' handling. */ // public: bool IsZoomed() { // return mainLayout.getZoomedPart() != null; // } /** * @return The currently maxmized stack (if any) */ // public: PartStack::Pointer GetMaximizedStack() { // return maximizedStack; // } /** * Sets the currently maximized stack. Used for query * and 'unZoom' purposes in the 3.3 presentation. * * @param stack The newly maximized stack */ // public: void SetMaximizedStack(PartStack::Pointer stack) { // if (stack == maximizedStack) // return; // // maximizedStack = stack; // } /** * Returns the ratio that should be used when docking the given source * part onto the given target * * @param source newly added part * @param target existing part being dragged over * @return the final size of the source part (wrt the current size of target) * after it is docked */ public: static float GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target); /** * Returns whether changes to a part will affect zoom. There are a few * conditions for this .. - we are zoomed. - the part is contained in the * main window. - the part is not the zoom part - the part is not a fast * view - the part and the zoom part are not in the same editor workbook * - the part and the zoom part are not in the same view stack. */ // public: bool PartChangeAffectsZoom(LayoutPart::Pointer pane) { // return pane.isObscuredByZoom(); // } /** * Remove all references to a part. */ public: void RemovePart(LayoutPart::Pointer part); /** * Add a part to the presentation. * * Note: unlike all other LayoutParts, PartPlaceholders will still point to * their parent container even when it is inactive. This method relies on this * fact to locate the parent. */ public: void ReplacePlaceholderWithPart(LayoutPart::Pointer part); /** * @see org.blueberry.ui.IPersistable */ public: bool RestoreState(IMemento::Pointer memento); /** * @see org.blueberry.ui.IPersistable */ public: bool SaveState(IMemento::Pointer memento); /** * Zoom in on a particular layout part. */ // public: void zoomIn(IWorkbenchPartReference ref) { // PartPane pane = ((WorkbenchPartReference) ref).getPane(); // // // parentWidget.setRedraw(false); // try { // pane.requestZoomIn(); // } finally { // parentWidget.setRedraw(true); // } // } /** * Zoom out. */ // public: void zoomOut() { // // New 3.3 behavior // if (Perspective.useNewMinMax(perspective)) { // if (maximizedStack != null) // maximizedStack.setState(IStackPresentationSite.STATE_RESTORED); // return; // } // // LayoutPart zoomPart = mainLayout.getZoomedPart(); // if (zoomPart != null) { // zoomPart.requestZoomOut(); // } // } /** * Forces the perspective to have no zoomed or minimized parts. * This is used when switching to the 3.3 presentation... */ // public: void forceNoZoom() { // // Ensure that nobody's zoomed // zoomOut(); // // // Now, walk the layout ensuring that nothing is minimized // LayoutPart[] kids = mainLayout.getChildren(); // for (int i = 0; i < kids.length; i++) { // if (kids[i] instanceof ViewStack) { // ((ViewStack)kids[i]).setMinimized(false); // } // else if (kids[i] instanceof EditorSashContainer) { // LayoutPart[] editorStacks = ((EditorSashContainer)kids[i]).getChildren(); // for (int j = 0; j < editorStacks.length; j++) { // if (editorStacks[j] instanceof EditorStack) { // ((EditorStack)editorStacks[j]).setMinimized(false); // } // } // } // } // } /** * Captures the current bounds of all ViewStacks and the editor - * area and puts them into an ID -> Rectangle map. This info is + * area and puts them into an ID -> QRect map. This info is * used to cache the bounds so that we can correctly place minimized * stacks during a 'maximized' operation (where the iterative min's * affect the current layout while being performed. */ public: void UpdateBoundsMap(); /** * Resets the bounds map so that it won't interfere with normal minimize * operations */ public: void ResetBoundsMap(); public: - Rectangle GetCachedBoundsFor(const QString& id); + QRect GetCachedBoundsFor(const QString& id); }; } #endif /* BERRYPERSPECTIVEHELPER_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 be77a816cc..388643890a 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) +void PresentablePart::SetBounds(const QRect& 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; } QIcon PresentablePart::GetTitleImage() { if (enableOutputs) { return this->GetPartReference()->GetTitleImage(); } // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); 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 9e30b854a0..2ae7df9400 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) 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; + QRect 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) + * @see org.blueberry.ui.presentations.IPresentablePart#setBounds(org.blueberry.swt.graphics.QRect) */ - void SetBounds(const Rectangle& bounds); + void SetBounds(const QRect& 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() */ 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/berryQtDnDTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.cpp deleted file mode 100755 index 43e21a8551..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.cpp +++ /dev/null @@ -1,33 +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 "berryQtDnDTweaklet.h" - -#include "berryQtTracker.h" - -namespace berry { - -QtDnDTweaklet::QtDnDTweaklet() -{ - -} - -ITracker* QtDnDTweaklet::CreateTracker() -{ - return new QtTracker(); -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h deleted file mode 100755 index 78b7cf5e24..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h +++ /dev/null @@ -1,39 +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 BERRYQTDNDTWEAKLET_H_ -#define BERRYQTDNDTWEAKLET_H_ - -#include - -namespace berry { - -class QtDnDTweaklet : public QObject, public DnDTweaklet -{ - Q_OBJECT - Q_INTERFACES(berry::DnDTweaklet) - -public: - - QtDnDTweaklet(); - - ITracker* CreateTracker(); -}; - -} - -#endif /* BERRYQTDNDTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp index 7ced1614c1..86e407a37e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp @@ -1,207 +1,203 @@ /*=================================================================== 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 "berryQtShell.h" #include "berryQtWidgetsTweakletImpl.h" #include "berryQtMainWindowControl.h" #include #include #include #include #include namespace berry { QtShell::QtShell(QWidget* parent, Qt::WindowFlags flags) : updatesDisabled(false) { if (parent == 0 || flags.testFlag(Qt::Window)) { widget = new QtMainWindowControl(this, parent, flags); widget->setUpdatesEnabled(false); updatesDisabled = true; widget->setAttribute(Qt::WA_DeleteOnClose); } else { widget = new QtControlWidget(parent, this, flags | Qt::Dialog); widget->setObjectName("shell widget"); } widget->setProperty("shell", QVariant::fromValue(static_cast(this))); } QtShell::~QtShell() { widget->deleteLater(); } -void QtShell::SetBounds(const Rectangle& bounds) +void QtShell::SetBounds(const QRect& bounds) { - widget->move(bounds.x, bounds.y); - widget->resize(bounds.width, bounds.height); + widget->setGeometry(bounds); } -Rectangle QtShell::GetBounds() const +QRect QtShell::GetBounds() const { - const QRect& qRect = widget->frameGeometry(); - const QSize& size = widget->size(); - Rectangle rect(qRect.x(), qRect.y(), size.width(), size.height()); - return rect; + return widget->frameGeometry(); } void QtShell::SetLocation(int x, int y) { widget->move(x, y); } -Point QtShell::ComputeSize(int /*wHint*/, int /*hHint*/, bool changed) +QPoint QtShell::ComputeSize(int /*wHint*/, int /*hHint*/, bool changed) { if (changed) widget->updateGeometry(); QSize size(widget->size()); - Point point(size.width(), size.height()); + QPoint point(size.width(), size.height()); return point; } QString QtShell::GetText() const { return widget->windowTitle(); } void QtShell::SetText(const QString& title) { widget->setWindowTitle(title); widget->setObjectName(title); } bool QtShell::IsVisible() { return widget->isVisible(); } void QtShell::SetVisible(bool visible) { widget->setVisible(visible); } void QtShell::SetActive() { widget->activateWindow(); widget->raise(); } QWidget *QtShell::GetControl() { return widget; } void QtShell::SetImages(const QList& /*images*/) { } bool QtShell::GetMaximized() { return widget->isMaximized(); } bool QtShell::GetMinimized() { return widget->isMinimized(); } void QtShell::SetMaximized(bool maximized) { maximized ? widget->showMaximized() : widget->showNormal(); } void QtShell::SetMinimized(bool minimized) { minimized ? widget->showMinimized() : widget->showNormal(); } void QtShell::AddShellListener(IShellListener* listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); poco_assert(variant.isValid()); QtWidgetController::Pointer controller = variant.value(); poco_assert(controller != 0); controller->AddShellListener(listener); } void QtShell::RemoveShellListener(IShellListener* listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); if (controller != 0) controller->RemoveShellListener(listener); } } void QtShell::Open(bool block) { if (updatesDisabled) { widget->setUpdatesEnabled(true); updatesDisabled = false; } widget->setWindowModality(block ? Qt::WindowModal : Qt::NonModal); widget->show(); } void QtShell::Close() { widget->close(); } QList QtShell::GetShells() { GuiWidgetsTweaklet* widgetTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); QList allShells(widgetTweaklet->GetShells()); QList descendants; for (int i = 0; i < allShells.size(); ++i) { Shell::Pointer shell = allShells[i]; if (widgetTweaklet->GetShell(shell->GetControl()) == this) { descendants.push_back(shell); } } return descendants; } Qt::WindowFlags QtShell::GetStyle() const { return widget->windowFlags(); } QWidget* QtShell::GetWidget() { return widget; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h index eada61c8e5..5b930568fb 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h @@ -1,86 +1,85 @@ /*=================================================================== 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 BERRYQTMAINWINDOWSHELL_H_ #define BERRYQTMAINWINDOWSHELL_H_ #include -#include #include namespace berry { class QtAbstractControlWidget; class QtShell : public Shell { public: QtShell(QWidget* parent = 0, Qt::WindowFlags flags = 0); ~QtShell(); // berry::Shell - void SetBounds(const Rectangle& bounds); - Rectangle GetBounds() const; + void SetBounds(const QRect& bounds); + QRect GetBounds() const; void SetLocation(int x, int y); - Point ComputeSize(int wHint, int hHint, bool changed); + QPoint ComputeSize(int wHint, int hHint, bool changed); QString GetText() const; void SetText(const QString& text); bool IsVisible(); void SetVisible(bool visible); void SetActive(); QWidget* GetControl(); void SetImages(const QList& images); bool GetMaximized(); bool GetMinimized(); void SetMaximized(bool maximized); void SetMinimized(bool minimized); void AddShellListener(IShellListener* listener); void RemoveShellListener(IShellListener* listener); void Open(bool block = false); void Close(); QList GetShells(); Qt::WindowFlags GetStyle () const; QWidget* GetWidget(); private: QWidget* widget; bool updatesDisabled; }; } #endif /* BERRYQTMAINWINDOWSHELL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp index 47e58876ec..b268f5dba2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp @@ -1,249 +1,287 @@ /*=================================================================== 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 "berryQtTracker.h" +#include "berryConstants.h" + #include #include #include +#include +#include namespace berry { +CursorType QtDragManager::PositionToCursorType(int positionConstant) +{ + if (positionConstant == Constants::LEFT) + return CURSOR_LEFT; + if (positionConstant == Constants::RIGHT) + return CURSOR_RIGHT; + if (positionConstant == Constants::TOP) + return CURSOR_TOP; + if (positionConstant == Constants::BOTTOM) + return CURSOR_BOTTOM; + if (positionConstant == Constants::CENTER) + return CURSOR_CENTER; + + return CURSOR_INVALID; +} + +int QtDragManager::CursorTypeToPosition(CursorType dragCursorId) +{ + switch (dragCursorId) + { + case CURSOR_LEFT: + return Constants::LEFT; + case CURSOR_RIGHT: + return Constants::RIGHT; + case CURSOR_TOP: + return Constants::TOP; + case CURSOR_BOTTOM: + return Constants::BOTTOM; + case CURSOR_CENTER: + return Constants::CENTER; + default: + return Constants::DEFAULT; + } +} + bool QtDragManager::eventFilter(QObject* o, QEvent* e) { if (beingCancelled) { if (e->type() == QEvent::KeyRelease && ((QKeyEvent*) e)->key() == Qt::Key_Escape) { QApplication::instance()->removeEventFilter(this); beingCancelled = false; eventLoop->exit(); return true; // block the key release } return false; } if (!o->isWidgetType()) return false; if (e->type() == QEvent::MouseMove) { QMouseEvent* me = (QMouseEvent *) e; this->Move(me->globalPos()); return true; } else if (e->type() == QEvent::MouseButtonRelease) { //DEBUG("pre drop"); QApplication::instance()->removeEventFilter(this); beingCancelled = false; eventLoop->exit(); return true; } if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) { QKeyEvent *ke = ((QKeyEvent*) e); if (ke->key() == Qt::Key_Escape && e->type() == QEvent::KeyPress) { this->Cancel(); QApplication::instance()->removeEventFilter(this); //beingCancelled = false; eventLoop->exit(); } else { // move(QCursor::pos()); } return true; // Eat all key events } // ### We bind modality to widgets, so we have to do this // ### "manually". // DnD is modal - eat all other interactive events switch (e->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::Wheel: case QEvent::ShortcutOverride: #ifdef QT3_SUPPORT case QEvent::Accel: case QEvent::AccelAvailable: #endif return true; default: return false; } } void QtDragManager::Cancel() { beingCancelled = true; } void QtDragManager::Move(const QPoint& globalPos) { tracker->HandleMove(globalPos); } bool QtDragManager::Drag(QtTracker* tracker) { if (tracker == 0) return false; this->tracker = tracker; beingCancelled = false; QApplication::instance()->installEventFilter(this); // if (!QWidget::mouseGrabber()) // rubberBand->grabMouse(); eventLoop = new QEventLoop; eventLoop->exec(); delete eventLoop; eventLoop = 0; return !beingCancelled; } QtTracker::QtTracker() : rubberBand(0), dragManager(0), cursorOverride(0) { rubberBand = new QRubberBand(QRubberBand::Rectangle); QPalette rubberPalette(rubberBand->palette()); //rubberPalette.setColor(QPalette::Button, QColor(Qt::darkRed)); rubberPalette.setBrush(QPalette::Foreground, QBrush(Qt::darkRed)); rubberPalette.setBrush(QPalette::Window, QBrush(Qt::darkRed)); rubberPalette.setBrush(QPalette::Background, QBrush(Qt::darkRed)); rubberPalette.setBrush(QPalette::Base, QBrush(Qt::darkRed)); rubberPalette.setBrush(QPalette::Text, QBrush(Qt::darkRed)); rubberBand->setPalette(rubberPalette); rubberBand->ensurePolished(); QPixmap pixCursorTop(":/org.blueberry.ui.qt/cursor_top.xpm"); QCursor* cursorTop = new QCursor(pixCursorTop, 15, 8); - cursorMap.insert(DnDTweaklet::CURSOR_TOP, cursorTop); + cursorMap.insert(CURSOR_TOP, cursorTop); QPixmap pixCursorRight(":/org.blueberry.ui.qt/cursor_right.xpm"); QCursor* cursorRight = new QCursor(pixCursorRight, 23, 15); - cursorMap.insert(DnDTweaklet::CURSOR_RIGHT, cursorRight); + cursorMap.insert(CURSOR_RIGHT, cursorRight); QPixmap pixCursorBottom(":/org.blueberry.ui.qt/cursor_bottom.xpm"); QCursor* cursorBottom = new QCursor(pixCursorBottom, 16, 23); - cursorMap.insert(DnDTweaklet::CURSOR_BOTTOM, cursorBottom); + cursorMap.insert(CURSOR_BOTTOM, cursorBottom); QPixmap pixCursorLeft(":/org.blueberry.ui.qt/cursor_left.xpm"); QCursor* cursorLeft = new QCursor(pixCursorLeft, 8, 15); - cursorMap.insert(DnDTweaklet::CURSOR_LEFT, cursorLeft); + cursorMap.insert(CURSOR_LEFT, cursorLeft); QPixmap pixCursorCenter(":/org.blueberry.ui.qt/cursor_center.xpm"); QCursor* cursorCenter = new QCursor(pixCursorCenter, 15, 15); - cursorMap.insert(DnDTweaklet::CURSOR_CENTER, cursorCenter); + cursorMap.insert(CURSOR_CENTER, cursorCenter); QPixmap pixCursorOffscreen(":/org.blueberry.ui.qt/cursor_offscreen.xpm"); QCursor* cursorOffscreen = new QCursor(pixCursorOffscreen, 15, 15); - cursorMap.insert(DnDTweaklet::CURSOR_OFFSCREEN, cursorOffscreen); + cursorMap.insert(CURSOR_OFFSCREEN, cursorOffscreen); QCursor* cursorInvalid = new QCursor(Qt::ForbiddenCursor); - cursorMap.insert(DnDTweaklet::CURSOR_INVALID, cursorInvalid); + cursorMap.insert(CURSOR_INVALID, cursorInvalid); } QtTracker::~QtTracker() { delete rubberBand; - for (QHash::iterator iter = cursorMap.begin(); + for (QHash::iterator iter = cursorMap.begin(); iter != cursorMap.end(); ++iter) { delete iter.value(); } } -Rectangle QtTracker::GetRectangle() +QRect QtTracker::GetRectangle() const { - const QRect& rect = rubberBand->geometry(); - return Rectangle(rect.x(), rect.y(), rect.width(), rect.height()); + return rubberBand->geometry(); } -void QtTracker::SetRectangle(const Rectangle& rectangle) +void QtTracker::SetRectangle(const QRect& rectangle) { - rubberBand->setGeometry(rectangle.x, rectangle.y, rectangle.width, rectangle.height); + rubberBand->setGeometry(rectangle); } -void QtTracker::SetCursor(DnDTweaklet::CursorType cursorType) +void QtTracker::SetCursor(CursorType cursorType) { QCursor* cursor = cursorMap[cursorType]; if (!cursor) return; if (cursorOverride > 0) { QApplication::changeOverrideCursor(*cursor); } else { ++cursorOverride; QApplication::setOverrideCursor(*cursor); } } bool QtTracker::Open() { rubberBand->show(); dragManager = new QtDragManager(); bool result = dragManager->Drag(this); delete dragManager; rubberBand->hide(); while (cursorOverride > 0) { QApplication::restoreOverrideCursor(); --cursorOverride; } return result; } void QtTracker::AddControlListener(GuiTk::IControlListener::Pointer listener) { controlEvents.AddListener(listener); } void QtTracker::RemoveControlListener(GuiTk::IControlListener::Pointer listener) { controlEvents.RemoveListener(listener); } void QtTracker::HandleMove(const QPoint& globalPoint) { GuiTk::ControlEvent::Pointer event( new GuiTk::ControlEvent(this, globalPoint.x(), globalPoint.y(), 0, 0)); controlEvents.movedEvent(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h index bf7c14327e..2d79d80b35 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h @@ -1,97 +1,111 @@ /*=================================================================== 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 BERRYQTTRACKER_H_ #define BERRYQTTRACKER_H_ -#include -#include +#include #include -#include -#include -#include -#include - -#include +class QCursor; +class QEventLoop; +class QRubberBand; namespace berry { class QtTracker; class QtDragManager : public QObject { Q_OBJECT private: QtTracker* tracker; QEventLoop* eventLoop; bool beingCancelled; protected: bool eventFilter(QObject* o, QEvent* e); void Cancel(); void Move(const QPoint& globalPos); public: + static CursorType PositionToCursorType(int positionConstant); + + /** + * Converts a DnDTweaklet::CursorType (CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER) into a BlueBerry constant + * (Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM, Constants::CENTER) + * + * @param dragCursorId + * @return a BlueBerry Constants::* constant + */ + static int CursorTypeToPosition(CursorType dragCursorId); + bool Drag(QtTracker* tracker); }; - -class QtTracker : public ITracker { +/** + * Instances of this class implement a rubber banding rectangle that is + * drawn onto a parent control or display. + * These rectangles can be specified to respond to mouse and key events + * by either moving or resizing themselves accordingly. Trackers are + * typically used to represent window geometries in a lightweight manner. + * + */ +class QtTracker { private: QRubberBand* rubberBand; QtDragManager* dragManager; int cursorOverride; GuiTk::IControlListener::Events controlEvents; - QHash cursorMap; + QHash cursorMap; public: QtTracker(); ~QtTracker(); - Rectangle GetRectangle(); - void SetRectangle(const Rectangle& rectangle); + QRect GetRectangle() const; + void SetRectangle(const QRect& rectangle); - void SetCursor(DnDTweaklet::CursorType cursor); + void SetCursor(CursorType cursor); bool Open(); void AddControlListener(GuiTk::IControlListener::Pointer listener); void RemoveControlListener(GuiTk::IControlListener::Pointer listener); void HandleMove(const QPoint& globalPoint); }; } #endif /* BERRYQTTRACKER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.cpp index 56fb8a0272..136603bf55 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.cpp @@ -1,275 +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 "berryQtWidgetsTweaklet.h" #include #include namespace berry { QtWidgetsTweaklet::QtWidgetsTweaklet() { } void QtWidgetsTweaklet::AddSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) { impl.AddSelectionListener(static_cast(widget), listener); } void QtWidgetsTweaklet::RemoveSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) { impl.RemoveSelectionListener(static_cast(widget), listener); } -Rectangle QtWidgetsTweaklet::GetScreenSize(int i) +QRect QtWidgetsTweaklet::GetScreenSize(int i) { return impl.GetScreenSize(i); } unsigned int QtWidgetsTweaklet::GetScreenNumber() { return impl.GetScreenNumber(); } int QtWidgetsTweaklet::GetPrimaryScreenNumber() { return impl.GetPrimaryScreenNumber(); } -Rectangle QtWidgetsTweaklet::GetAvailableScreenSize(int i) +QRect QtWidgetsTweaklet::GetAvailableScreenSize(int i) { return impl.GetAvailableScreenSize(i); } -int QtWidgetsTweaklet::GetClosestScreenNumber(const Rectangle& rect) +int QtWidgetsTweaklet::GetClosestScreenNumber(const QRect& rect) { return impl.GetClosestScreenNumber(rect); } //IMenu::Pointer QtWidgetsTweaklet::CreateMenu(void*, IMenu::Style style) //{ // //TODO Qt CreateMenu // return IMenu::Pointer(0); //} //IMenu::Pointer QtWidgetsTweaklet::CreateMenu(IMenu::Pointer parent) //{ // //TODO Qt CreateMenu // return IMenu::Pointer(0); //} //IMenuItem::Pointer QtWidgetsTweaklet::CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index) //{ // //TODO Qt CreateMenuItem // return IMenuItem::Pointer(0); //} void QtWidgetsTweaklet::AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener) { QWidget* qwidget = static_cast(widget); QVariant variant = qwidget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); if (controller != 0) impl.AddControlListener(controller.GetPointer(), listener); } } void QtWidgetsTweaklet::RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener) { QWidget* qwidget = static_cast(widget); QVariant variant = qwidget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); if (controller != 0) impl.RemoveControlListener(controller.GetPointer(), listener); } } bool QtWidgetsTweaklet::GetEnabled(void* widget) { return impl.GetEnabled(static_cast(widget)); } void QtWidgetsTweaklet::SetEnabled(void* widget, bool enabled) { impl.SetEnabled(static_cast(widget), enabled); } -void QtWidgetsTweaklet::SetBounds(void* widget, const Rectangle& bounds) +void QtWidgetsTweaklet::SetBounds(void* widget, const QRect& bounds) { impl.SetBounds(static_cast(widget), bounds); } -Rectangle QtWidgetsTweaklet::GetBounds(void* widget) +QRect QtWidgetsTweaklet::GetBounds(void* widget) { return impl.GetBounds(static_cast(widget)); } void QtWidgetsTweaklet::SetVisible(void* widget, bool visible) { impl.SetVisible(static_cast(widget), visible); } bool QtWidgetsTweaklet::GetVisible(void* widget) { return impl.GetVisible(static_cast(widget)); } bool QtWidgetsTweaklet::IsVisible(void* widget) { return impl.IsVisible(static_cast(widget)); } -Rectangle QtWidgetsTweaklet::GetClientArea(void* widget) +QRect QtWidgetsTweaklet::GetClientArea(void* widget) { return impl.GetClientArea(static_cast(widget)); } void* QtWidgetsTweaklet::GetParent(void* widget) { return impl.GetParent(static_cast(widget)); } bool QtWidgetsTweaklet::SetParent(void* widget, void* parent) { return impl.SetParent(static_cast(widget), static_cast(parent)); } void QtWidgetsTweaklet::SetData(void* widget, const QString& id, Object::Pointer data) { impl.SetData(static_cast(widget), id, data); } Object::Pointer QtWidgetsTweaklet::GetData(void* widget, const QString& id) { return impl.GetData(static_cast(widget), id); } -Point QtWidgetsTweaklet::GetCursorLocation() +QPoint QtWidgetsTweaklet::GetCursorLocation() { return impl.GetCursorLocation(); } void* QtWidgetsTweaklet::GetCursorControl() { return impl.GetCursorControl(); } -void* QtWidgetsTweaklet::FindControl(const QList& shells, const Point& location) +void* QtWidgetsTweaklet::FindControl(const QList& shells, const QPoint& location) { return impl.FindControl(shells, location); } bool QtWidgetsTweaklet::IsChild(void* parentToTest, void* childToTest) { return impl.IsChild(static_cast(parentToTest), static_cast(childToTest)); } void* QtWidgetsTweaklet::GetFocusControl() { return impl.GetFocusControl(); } bool QtWidgetsTweaklet::IsReparentable(void* widget) { return impl.IsReparentable(static_cast(widget)); } void QtWidgetsTweaklet::MoveAbove(void* widgetToMove, void* widget) { impl.MoveAbove(static_cast(widgetToMove), static_cast(widget)); } void QtWidgetsTweaklet::MoveBelow(void* widgetToMove, void* widget) { impl.MoveBelow(static_cast(widgetToMove), static_cast(widget)); } void QtWidgetsTweaklet::Dispose(void* widget) { impl.Dispose(static_cast(widget)); } Shell::Pointer QtWidgetsTweaklet::CreateShell(Shell::Pointer parent, int style) { return impl.CreateShell(parent, style); } void* QtWidgetsTweaklet::CreateComposite(void* parent) { return impl.CreateComposite(static_cast(parent)); } void QtWidgetsTweaklet::DisposeShell(Shell::Pointer shell) { impl.DisposeShell(shell); } QList QtWidgetsTweaklet::GetShells() { return impl.GetShells(); } Shell::Pointer QtWidgetsTweaklet::GetShell(void* widget) { return impl.GetShell(static_cast(widget)); } Shell::Pointer QtWidgetsTweaklet::GetActiveShell() { return impl.GetActiveShell(); } -Rectangle QtWidgetsTweaklet::ToControl(void* coordinateSystem, - const Rectangle& toConvert) +QRect QtWidgetsTweaklet::ToControl(void* coordinateSystem, + const QRect& toConvert) { return impl.ToControl(static_cast(coordinateSystem), toConvert); } -Point QtWidgetsTweaklet::ToControl(void* coordinateSystem, - const Point& toConvert) +QPoint QtWidgetsTweaklet::ToControl(void* coordinateSystem, + const QPoint& toConvert) { return impl.ToControl(static_cast(coordinateSystem), toConvert); } -Rectangle QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, - const Rectangle& toConvert) +QRect QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, + const QRect& toConvert) { return impl.ToDisplay(static_cast(coordinateSystem), toConvert); } -Point QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, - const Point& toConvert) +QPoint QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, + const QPoint& toConvert) { return impl.ToDisplay(static_cast(coordinateSystem), toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h index e4cab00e33..65bbfdc98d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h @@ -1,131 +1,131 @@ /*=================================================================== 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 BERRYQTWIDGETSTWEAKLET_H_ #define BERRYQTWIDGETSTWEAKLET_H_ #include #include "berryQtWidgetsTweakletImpl.h" namespace berry { class QtWidgetsTweaklet : public QObject, public GuiWidgetsTweaklet { Q_OBJECT Q_INTERFACES(berry::GuiWidgetsTweaklet) public: QtWidgetsTweaklet(); void AddSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener); void RemoveSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener); void AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener); void RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener); bool GetEnabled(void* widget); void SetEnabled(void* widget, bool enabled); - void SetBounds(void* widget, const Rectangle& bounds); - Rectangle GetBounds(void* widget); + void SetBounds(void* widget, const QRect& bounds); + QRect GetBounds(void* widget); void SetVisible(void* widget, bool visible); bool GetVisible(void* widget); bool IsVisible(void* widget); - Rectangle GetClientArea(void* widget); + QRect GetClientArea(void* widget); void* GetParent(void* widget); bool SetParent(void* widget, void* parent); void SetData(void* widget, const QString& id, Object::Pointer data); Object::Pointer GetData(void* widget, const QString& id); //IMenu::Pointer CreateMenu(void*, IMenu::Style = IMenu::POP_UP); //IMenu::Pointer CreateMenu(IMenu::Pointer parent); //IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1); - Rectangle GetScreenSize(int i = -1); + QRect GetScreenSize(int i = -1); unsigned int GetScreenNumber(); int GetPrimaryScreenNumber(); - Rectangle GetAvailableScreenSize(int i = -1); - int GetClosestScreenNumber(const Rectangle&); + QRect GetAvailableScreenSize(int i = -1); + int GetClosestScreenNumber(const QRect&); - Point GetCursorLocation(); + QPoint GetCursorLocation(); void* GetCursorControl(); - void* FindControl(const QList& shells, const Point& location); + void* FindControl(const QList& shells, const QPoint& location); /** * Determines if one control is a child of another. Returns true iff the second * argument is a child of the first (or the same object). * * @param potentialParent * @param childToTest * @return */ bool IsChild(void* potentialParent, void* childToTest); /** * Returns the control which currently has keyboard focus, * or null if keyboard events are not currently going to * any of the controls built by the currently running * application. * * @return the control under the cursor */ void* GetFocusControl(); bool IsReparentable(void* widget); void MoveAbove(void* widgetToMove, void* widget); void MoveBelow(void* widgetToMove, void* widget); void Dispose(void* widget); Shell::Pointer CreateShell(Shell::Pointer parent, int style); void DisposeShell(Shell::Pointer shell); void* CreateComposite(void* parent); QList GetShells(); Shell::Pointer GetShell(void* widget); Shell::Pointer GetActiveShell(); - Rectangle ToControl(void* coordinateSystem, - const Rectangle& toConvert); + QRect ToControl(void* coordinateSystem, + const QRect& toConvert); - Point ToControl(void* coordinateSystem, - const Point& toConvert); + QPoint ToControl(void* coordinateSystem, + const QPoint& toConvert); - Rectangle ToDisplay(void* coordinateSystem, - const Rectangle& toConvert); + QRect ToDisplay(void* coordinateSystem, + const QRect& toConvert); - Point ToDisplay(void* coordinateSystem, - const Point& toConvert); + QPoint ToDisplay(void* coordinateSystem, + const QPoint& toConvert); private: QtWidgetsTweakletImpl impl; }; } #endif /* BERRYQTWIDGETSTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp index 46f848cbcb..6f97075e5d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp @@ -1,449 +1,433 @@ /*=================================================================== 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 "berryQtWidgetsTweakletImpl.h" #include "berryQtSash.h" #include "berryQtShell.h" #include #include #include #include #include #include namespace berry { QtSelectionListenerWrapper::QtSelectionListenerWrapper(QWidget* w) : widget(w) { } void QtSelectionListenerWrapper::AddListener(GuiTk::ISelectionListener::Pointer listener) { QAbstractButton* button = qobject_cast(widget); if (button != 0) { this->connect(button, "clicked(bool)", this, "QAbstractButtonClicked(bool)"); selectionEvents.AddListener(listener); } BERRY_WARN << "WARNING: QtWidgetsTweaklet: no suitable type for listening for selections found!\n"; } int QtSelectionListenerWrapper::RemoveListener(GuiTk::ISelectionListener::Pointer listener) { selectionEvents.RemoveListener(listener); return static_cast(std::max(selectionEvents.selected.GetListeners().size(), selectionEvents.defaultSelected.GetListeners().size())); } void QtSelectionListenerWrapper::QAbstractButtonClicked(bool /*checked*/) { GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(widget)); selectionEvents.selected(event); } void QtWidgetsTweakletImpl::AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { if (widget == 0) return; // special handling for berry::QtSash QtSash* sash = qobject_cast(widget); if (sash != 0) { sash->AddSelectionListener(listener); return; } // "normal" Qt widgets get wrapped QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget]; if (wrapper == 0) { wrapper = new QtSelectionListenerWrapper(widget); selectionListenerMap[widget] = wrapper; } wrapper->AddListener(listener); } void QtWidgetsTweakletImpl::RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { if (widget == 0) return; // special handling for berry::QtSash QtSash* sash = qobject_cast(widget); if (sash != 0) { sash->RemoveSelectionListener(listener); return; } QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget]; if (wrapper == 0) return; if (wrapper->RemoveListener(listener) == 0) { selectionListenerMap.remove(wrapper); delete wrapper; } } -Rectangle QtWidgetsTweakletImpl::GetScreenSize(int i) +QRect QtWidgetsTweakletImpl::GetScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); - QRect screenGeometry; - if (i < 0) screenGeometry = desktop->screen()->geometry(); - else screenGeometry = desktop->screenGeometry(i); - - return (Rectangle(screenGeometry.x(), screenGeometry.y() - , screenGeometry.width(), screenGeometry.height())); + if (i < 0) return desktop->screen()->geometry(); + return desktop->screenGeometry(i); } unsigned int QtWidgetsTweakletImpl::GetScreenNumber() { QDesktopWidget *desktop = QApplication::desktop(); // get the primary screen unsigned int numScreens = desktop->numScreens(); return numScreens; } int QtWidgetsTweakletImpl::GetPrimaryScreenNumber() { QDesktopWidget *desktop = QApplication::desktop(); // get the primary screen int primaryScreenNr = desktop->primaryScreen(); return primaryScreenNr; } -Rectangle QtWidgetsTweakletImpl::GetAvailableScreenSize(int i) +QRect QtWidgetsTweakletImpl::GetAvailableScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); - QRect screenGeometry; - if (i < 0) screenGeometry = desktop->screen()->geometry(); - else screenGeometry = desktop->availableGeometry(i); - - return (Rectangle(screenGeometry.x(), screenGeometry.y() - , screenGeometry.width(), screenGeometry.height())); + if (i < 0) return desktop->screen()->geometry(); + return desktop->availableGeometry(i); } -int QtWidgetsTweakletImpl::GetClosestScreenNumber(const Rectangle& r) +int QtWidgetsTweakletImpl::GetClosestScreenNumber(const QRect& r) { QDesktopWidget *desktop = QApplication::desktop(); - return desktop->screenNumber(QPoint(r.x + r.width/2, r.y + r.height/2)); + return desktop->screenNumber(QPoint(r.x() + r.width()/2, r.y() + r.height()/2)); } void QtWidgetsTweakletImpl::AddControlListener(QtWidgetController* controller, GuiTk::IControlListener::Pointer listener) { controller->AddControlListener(listener); } void QtWidgetsTweakletImpl::RemoveControlListener(QtWidgetController* controller, GuiTk::IControlListener::Pointer listener) { controller->RemoveControlListener(listener); } bool QtWidgetsTweakletImpl::GetEnabled(QWidget* widget) { return widget->isEnabled(); } void QtWidgetsTweakletImpl::SetEnabled(QWidget* widget, bool enabled) { widget->setEnabled(enabled); } -void QtWidgetsTweakletImpl::SetBounds(QWidget* widget, const Rectangle& bounds) +void QtWidgetsTweakletImpl::SetBounds(QWidget* widget, const QRect& bounds) { - widget->setGeometry(bounds.x, bounds.y, bounds.width, bounds.height); + widget->setGeometry(bounds); } -Rectangle QtWidgetsTweakletImpl::GetBounds(QWidget* widget) +QRect QtWidgetsTweakletImpl::GetBounds(QWidget* widget) { const QRect& geometry = widget->geometry(); - Rectangle rect(geometry.x(), geometry.y(), geometry.width(), geometry.height()); + QRect rect(geometry.x(), geometry.y(), geometry.width(), geometry.height()); return rect; } void QtWidgetsTweakletImpl::SetVisible(QWidget* widget, bool visible) { widget->setVisible(visible); } bool QtWidgetsTweakletImpl::GetVisible(QWidget* widget) { return !widget->isHidden(); } bool QtWidgetsTweakletImpl::IsVisible(QWidget* widget) { return widget->isVisible(); } -Rectangle QtWidgetsTweakletImpl::GetClientArea(QWidget* widget) +QRect QtWidgetsTweakletImpl::GetClientArea(QWidget* widget) { - const QRect& contentsRect = widget->contentsRect(); - Rectangle rect(contentsRect.x(), contentsRect.y(), contentsRect.width(), contentsRect.height()); - return rect; + return widget->contentsRect(); } void* QtWidgetsTweakletImpl::GetParent(QWidget* widget) { return widget->parentWidget(); } bool QtWidgetsTweakletImpl::SetParent(QWidget* widget, QWidget* parent) { if (parent != widget->parentWidget()) { widget->setParent(parent); return true; } return false; } void QtWidgetsTweakletImpl::SetData(QWidget* object, const QString& id, Object::Pointer data) { if (object == 0) return; QVariant variant; if (data != 0) variant.setValue(data); object->setProperty(qPrintable(id), variant); } Object::Pointer QtWidgetsTweakletImpl::GetData(QWidget* object, const QString& id) { if (object == 0) return Object::Pointer(0); QVariant variant = object->property(qPrintable(id)); if (variant.isValid()) { return variant.value(); } return Object::Pointer(0); } -Point QtWidgetsTweakletImpl::GetCursorLocation() +QPoint QtWidgetsTweakletImpl::GetCursorLocation() { QPoint qpoint = QCursor::pos(); - return Point(qpoint.x(), qpoint.y()); + return QPoint(qpoint.x(), qpoint.y()); } QWidget* QtWidgetsTweakletImpl::GetCursorControl() { return QApplication::widgetAt(QCursor::pos()); } -QWidget* QtWidgetsTweakletImpl::FindControl(const QList& shells, const Point& location) +QWidget* QtWidgetsTweakletImpl::FindControl(const QList& shells, const QPoint& location) { for (QList::const_iterator iter = shells.begin(); iter != shells.end(); ++iter) { QWidget* shellWidget = static_cast((*iter)->GetControl()); - QWidget* control = shellWidget->childAt(location.x, location.y); + QWidget* control = shellWidget->childAt(location.x(), location.y()); if (control) return control; } return 0; } bool QtWidgetsTweakletImpl::IsChild(QObject* parentToTest, QObject* childToTest) { bool found = false; QObject* parent = childToTest->parent(); while (!found && parent != 0) { if (parent == parentToTest) found = true; parent = parent->parent(); } return found; } QWidget* QtWidgetsTweakletImpl::GetFocusControl() { return QApplication::focusWidget(); } bool QtWidgetsTweakletImpl::IsReparentable(QWidget* /*widget*/) { return true; } void QtWidgetsTweakletImpl::MoveAbove(QWidget* widgetToMove, QWidget* /*widget*/) { widgetToMove->raise(); } void QtWidgetsTweakletImpl::MoveBelow(QWidget* widgetToMove, QWidget* /*widget*/) { widgetToMove->lower(); } void QtWidgetsTweakletImpl::Dispose(QWidget* widget) { delete widget; widget = 0; } Shell::Pointer QtWidgetsTweakletImpl::CreateShell(Shell::Pointer parent, int style) { #ifdef __APPLE__ Qt::WindowFlags qtFlags(0); #else Qt::WindowFlags qtFlags(Qt::CustomizeWindowHint); #endif if (style & Constants::MAX) qtFlags |= Qt::WindowMaximizeButtonHint; if (style & Constants::MIN) qtFlags |= Qt::WindowMinimizeButtonHint; if (style & Constants::CLOSE) { qtFlags |= Qt::WindowSystemMenuHint; #if QT_VERSION >= 0x040500 qtFlags |= Qt::WindowCloseButtonHint; #endif } if (!(style & Constants::BORDER)) qtFlags |= Qt::FramelessWindowHint; if (style & Constants::TITLE) qtFlags |= Qt::WindowTitleHint; if (style & Constants::TOOL) qtFlags |= Qt::Tool; QWidget* parentWidget = 0; if (parent != 0) parentWidget = static_cast(parent->GetControl()); QtShell* qtshell = new QtShell(parentWidget, qtFlags); Shell::Pointer shell(qtshell); shellList.push_back(shell); if ((style & Constants::APPLICATION_MODAL) || (style & Constants::SYSTEM_MODAL)) qtshell->GetWidget()->setWindowModality(Qt::ApplicationModal); if (style & Constants::PRIMARY_MODAL) qtshell->GetWidget()->setWindowModality(Qt::WindowModal); return shell; } QWidget* QtWidgetsTweakletImpl::CreateComposite(QWidget* parent) { QWidget* composite = new QtControlWidget(parent, 0); composite->setObjectName("created composite"); return composite; } void QtWidgetsTweakletImpl::DisposeShell(Shell::Pointer shell) { shellList.removeAll(shell); } QList QtWidgetsTweakletImpl::GetShells() { return shellList; } Shell::Pointer QtWidgetsTweakletImpl::GetShell(QWidget* widget) { QWidget* qwindow = widget->window(); QVariant variant = qwindow->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); poco_assert(controller != 0); return controller->GetShell(); } return Shell::Pointer(0); } Shell::Pointer QtWidgetsTweakletImpl::GetActiveShell() { QWidget* qwidget = QApplication::activeWindow(); if (qwidget == 0) return Shell::Pointer(0); QVariant variant = qwidget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { return variant.value()->GetShell(); } return Shell::Pointer(0); } -Rectangle QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, - const Rectangle& toConvert) +QRect QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, + const QRect& toConvert) { - QPoint globalUpperLeft(toConvert.x, toConvert.y); - QPoint globalLowerRight(toConvert.x + toConvert.width, toConvert.y + toConvert.height); + QPoint globalUpperLeft = toConvert.topLeft(); + QPoint globalLowerRight = toConvert.bottomRight(); QPoint upperLeft = coordinateSystem->mapFromGlobal(globalUpperLeft); QPoint lowerRight = coordinateSystem->mapFromGlobal(globalLowerRight); - return Rectangle(upperLeft.x(), upperLeft.y(), lowerRight.x() - upperLeft.x(), + return QRect(upperLeft.x(), upperLeft.y(), lowerRight.x() - upperLeft.x(), lowerRight.y() - upperLeft.y()); } -Point QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, - const Point& toConvert) +QPoint QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, + const QPoint& toConvert) { - QPoint displayPoint(toConvert.x, toConvert.y); - - QPoint localPoint = coordinateSystem->mapFromGlobal(displayPoint); - return Point(localPoint.x(), localPoint.y()); + return coordinateSystem->mapFromGlobal(toConvert); } -Rectangle QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, - const Rectangle& toConvert) +QRect QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, + const QRect& toConvert) { - QPoint upperLeft(toConvert.x, toConvert.y); - QPoint lowerRight(toConvert.x + toConvert.width, toConvert.y + toConvert.height); + QPoint upperLeft = toConvert.topLeft(); + QPoint lowerRight = toConvert.bottomRight(); QPoint globalUpperLeft = coordinateSystem->mapToGlobal(upperLeft); QPoint globalLowerRight = coordinateSystem->mapToGlobal(lowerRight); - return Rectangle(globalUpperLeft.x(), globalUpperLeft.y(), globalLowerRight.x() - globalUpperLeft.x(), + return QRect(globalUpperLeft.x(), globalUpperLeft.y(), globalLowerRight.x() - globalUpperLeft.x(), globalLowerRight.y() - globalUpperLeft.y()); } -Point QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, - const Point& toConvert) +QPoint QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, + const QPoint& toConvert) { - QPoint localPoint(toConvert.x, toConvert.y); - QPoint displayPoint = coordinateSystem->mapToGlobal(localPoint); - - return Point(displayPoint.x(), displayPoint.y()); + return coordinateSystem->mapToGlobal(toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h index 843e112c8a..d880b1038c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h @@ -1,157 +1,156 @@ /*=================================================================== 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 BERRYQTWIDGETSTWEAKLETIMPL_H_ #define BERRYQTWIDGETSTWEAKLETIMPL_H_ #include -#include #include #include #include #include #include namespace berry { class QtSelectionListenerWrapper : public QObject { Q_OBJECT public: QtSelectionListenerWrapper(QWidget* widget); QWidget* widget; void AddListener(GuiTk::ISelectionListener::Pointer listener); int RemoveListener(GuiTk::ISelectionListener::Pointer listener); protected slots: void QAbstractButtonClicked(bool checked); private: GuiTk::ISelectionListener::Events selectionEvents; }; class QtWidgetsTweakletImpl { public: void AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener); void RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener); void AddControlListener(QtWidgetController* widget, GuiTk::IControlListener::Pointer listener); void RemoveControlListener(QtWidgetController* widget, GuiTk::IControlListener::Pointer listener); bool GetEnabled(QWidget* widget); void SetEnabled(QWidget* widget, bool enabled); - void SetBounds(QWidget* widget, const Rectangle& bounds); - Rectangle GetBounds(QWidget* widget); + void SetBounds(QWidget* widget, const QRect& bounds); + QRect GetBounds(QWidget* widget); void SetVisible(QWidget* widget, bool visible); bool GetVisible(QWidget* widget); bool IsVisible(QWidget* widget); - Rectangle GetClientArea(QWidget* widget); + QRect GetClientArea(QWidget* widget); void* GetParent(QWidget* widget); bool SetParent(QWidget* widget, QWidget* parent); void SetData(QWidget* widget, const QString& id, Object::Pointer data); Object::Pointer GetData(QWidget* widget, const QString& id); - Rectangle GetScreenSize(int i = -1); + QRect GetScreenSize(int i = -1); unsigned int GetScreenNumber(); int GetPrimaryScreenNumber(); - Rectangle GetAvailableScreenSize(int i = -1); - int GetClosestScreenNumber(const Rectangle&); + QRect GetAvailableScreenSize(int i = -1); + int GetClosestScreenNumber(const QRect&); - Point GetCursorLocation(); + QPoint GetCursorLocation(); QWidget* GetCursorControl(); - QWidget* FindControl(const QList& shells, const Point& location); + QWidget* FindControl(const QList& shells, const QPoint& location); /** * Determines if one control is a child of another. Returns true iff the second * argument is a child of the first (or the same object). * * @param potentialParent * @param childToTest * @return */ bool IsChild(QObject* potentialParent, QObject* childToTest); /** * Returns the control which currently has keyboard focus, * or null if keyboard events are not currently going to * any of the controls built by the currently running * application. * * @return the control under the cursor */ QWidget* GetFocusControl(); bool IsReparentable(QWidget* widget); void MoveAbove(QWidget* widgetToMove, QWidget* widget); void MoveBelow(QWidget* widgetToMove, QWidget* widget); void Dispose(QWidget* widget); Shell::Pointer CreateShell(Shell::Pointer parent, int style); void DisposeShell(Shell::Pointer shell); QWidget* CreateComposite(QWidget* parent); QList GetShells(); Shell::Pointer GetShell(QWidget* widget); Shell::Pointer GetActiveShell(); - Rectangle ToControl(QWidget* coordinateSystem, - const Rectangle& toConvert); + QRect ToControl(QWidget* coordinateSystem, + const QRect& toConvert); - Point ToControl(QWidget* coordinateSystem, - const Point& toConvert); + QPoint ToControl(QWidget* coordinateSystem, + const QPoint& toConvert); - Rectangle ToDisplay(QWidget* coordinateSystem, - const Rectangle& toConvert); + QRect ToDisplay(QWidget* coordinateSystem, + const QRect& toConvert); - Point ToDisplay(QWidget* coordinateSystem, - const Point& toConvert); + QPoint ToDisplay(QWidget* coordinateSystem, + const QPoint& toConvert); private: typedef QHash SelectionListenerMap; SelectionListenerMap selectionListenerMap; QList shellList; friend class QtShell; }; } #endif /* BERRYQTWIDGETSTWEAKLETIMPL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryTestDropLocation.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryTestDropLocation.h index 5aaacb1b32..769f914e56 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryTestDropLocation.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryTestDropLocation.h @@ -1,58 +1,57 @@ /*=================================================================== 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 BERRYTESTDROPLOCATION_H_ #define BERRYTESTDROPLOCATION_H_ #include -#include "berryPoint.h" #include "berryShell.h" #include namespace berry { /** * This is an interface intended for use in test suites. Objects can implement * this interface to force any dragged object to be dropped at a particular * location. * * @since 3.0 */ struct TestDropLocation : public Object { - berryObjectMacro(TestDropLocation); + berryObjectMacro(TestDropLocation) /** * Location where the object should be dropped, in display coordinates * * @return a location in display coordinates */ - virtual Point GetLocation() = 0; + virtual QPoint GetLocation() = 0; /** * The drop code will pretend that only the given shells are open, * and that they have the specified Z-order. * * @return the shells to check for drop targets, from bottom to top. */ virtual QList GetShells() = 0; }; } #endif /* BERRYTESTDROPLOCATION_H_ */ 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 c0ec3d0423..7d8feced30 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp @@ -1,4104 +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 #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; + int deltaWidth = width - pane->GetBounds().width(); if (sashInfo.right != 0) { - Rectangle rightBounds = sashInfo.rightNode->GetBounds(); + QRect rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio - sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x) - - rightBounds.x) / rightBounds.width); + 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(); + QRect leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio - sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x - deltaWidth) - - leftBounds.x) / leftBounds.width); + 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; + int deltaHeight = height - pane->GetBounds().height(); if (sashInfo.bottom != 0) { - Rectangle bottomBounds = sashInfo.bottomNode->GetBounds(); + QRect bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio - sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y) - - bottomBounds.y) / bottomBounds.height); + 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(); + QRect topBounds = sashInfo.topNode->GetBounds(); // set the ratio - sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y - deltaHeight) - - topBounds.y) / topBounds.height); + 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/berryWorkbenchPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp index 33a37a1805..a9c8571aae 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp @@ -1,393 +1,391 @@ /*=================================================================== 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 "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 "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(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/berryWorkbenchWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp index 1d82b3c991..5e9f60d5c8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp @@ -1,1961 +1,1963 @@ /*=================================================================== 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/berryGuiWidgetsTweaklet.h" #include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryIPerspectiveDescriptor.h" #include "berryUIException.h" #include "berryConstants.h" #include "berryIMenuService.h" #include "berryMenuUtil.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartSite.h" #include "berryIServiceLocatorCreator.h" #include "berryMenuManager.h" #include "berryQtControlWidget.h" #include "berryQtPerspectiveSwitcher.h" #include "berryWWinActionBars.h" #include "berryWorkbenchLocationService.h" #include "berryIServiceFactory.h" #include "berryIServiceScopes.h" #include "berryIEvaluationReference.h" #include "berryPlatformUI.h" #include "berryDebugUtil.h" #include #include #include namespace berry { const QString WorkbenchWindow::PROP_TOOLBAR_VISIBLE = "toolbarVisible"; const QString WorkbenchWindow::PROP_PERSPECTIVEBAR_VISIBLE = "perspectiveBarVisible"; const QString WorkbenchWindow::PROP_STATUS_LINE_VISIBLE = "statusLineVisible"; const ActionBarAdvisor::FillFlags WorkbenchWindow::FILL_ALL_ACTION_BARS = ActionBarAdvisor::FILL_MENU_BAR | ActionBarAdvisor::FILL_TOOL_BAR | ActionBarAdvisor::FILL_STATUS_LINE; WorkbenchWindow::WorkbenchWindow(int number) : Window(Shell::Pointer(0)) , pageComposite(0) , windowAdvisor(0) , actionBarAdvisor(0) , number(number) , largeUpdates(0) , closing(false) , shellActivated(false) , updateDisabled(true) , toolBarVisible(true) , perspectiveBarVisible(true) , statusLineVisible(true) , emptyWindowContentsCreated(false) , emptyWindowContents(0) , asMaximizedState(false) , partService(this) , serviceLocatorOwner(new ServiceLocatorOwner(this)) { this->Register(); // increase the reference count to avoid deleting // this object when temporary smart pointers // go out of scope // Make sure there is a workbench. This call will throw // an exception if workbench not created yet. IWorkbench* workbench = PlatformUI::GetWorkbench(); IServiceLocatorCreator* slc = workbench->GetService(); this->serviceLocator = slc->CreateServiceLocator( workbench, nullptr, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); InitializeDefaultServices(); // Add contribution managers that are exposed to other plugins. this->AddMenuBar(); //addCoolBar(SWT.NONE); // style is unused //addStatusLine(); this->FireWindowOpening(); // Fill the action bars this->FillActionBars(FILL_ALL_ACTION_BARS); this->UnRegister(false); // decrease reference count and avoid deleting // the window } WorkbenchWindow::~WorkbenchWindow() { //BERRY_INFO << "WorkbenchWindow::~WorkbenchWindow()"; } Object* WorkbenchWindow::GetService(const QString& key) { return serviceLocator->GetService(key); } bool WorkbenchWindow::HasService(const QString& key) const { return serviceLocator->HasService(key); } Shell::Pointer WorkbenchWindow::GetShell() const { return Window::GetShell(); } bool WorkbenchWindow::ClosePage(IWorkbenchPage::Pointer in, bool save) { // Validate the input. if (!pageList.Contains(in)) { return false; } WorkbenchPage::Pointer oldPage = in.Cast (); // Save old perspective. if (save && oldPage->IsSaveNeeded()) { if (!oldPage->SaveAllEditors(true)) { return false; } } // If old page is activate deactivate. bool oldIsActive = (oldPage == this->GetActivePage()); if (oldIsActive) { this->SetActivePage(IWorkbenchPage::Pointer(0)); } // Close old page. pageList.Remove(oldPage); partService.PageClosed(oldPage); //this->FirePageClosed(oldPage); //oldPage->Dispose(); // Activate new page. if (oldIsActive) { IWorkbenchPage::Pointer newPage = pageList.GetNextActive(); if (newPage != 0) { this->SetActivePage(newPage); } } if (!closing && pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } return true; } void WorkbenchWindow::AddPerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.AddListener(l); } void WorkbenchWindow::RemovePerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.RemoveListener(l); } IPerspectiveListener::Events& WorkbenchWindow::GetPerspectiveEvents() { return perspectiveEvents; } void WorkbenchWindow::FireWindowOpening() { // let the application do further configuration this->GetWindowAdvisor()->PreWindowOpen(); } void WorkbenchWindow::FireWindowRestored() { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->GetWindowAdvisor()->PostWindowRestore(); // } //}); } void WorkbenchWindow::FireWindowCreated() { this->GetWindowAdvisor()->PostWindowCreate(); } void WorkbenchWindow::FireWindowOpened() { this->GetWorkbenchImpl()->FireWindowOpened(IWorkbenchWindow::Pointer(this)); this->GetWindowAdvisor()->PostWindowOpen(); } bool WorkbenchWindow::FireWindowShellClosing() { return this->GetWindowAdvisor()->PreWindowShellClose(); } void WorkbenchWindow::FireWindowClosed() { // let the application do further deconfiguration this->GetWindowAdvisor()->PostWindowClose(); this->GetWorkbenchImpl()->FireWindowClosed(IWorkbenchWindow::Pointer(this)); } ///** // * Fires page activated // */ //void WorkbenchWindow::FirePageActivated(IWorkbenchPage::Pointer page) { //// String label = null; // debugging only //// if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { //// label = "activated " + page.getLabel(); //$NON-NLS-1$ //// } //// try { //// UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); //// UIListenerLogging.logPageEvent(this, page, //// UIListenerLogging.WPE_PAGE_ACTIVATED); // pageEvents.FirePageActivated(page); // partService.pageActivated(page); //// } finally { //// UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); //// } //} // ///** // * Fires page closed // */ //void WorkbenchWindow::FirePageClosed(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "closed " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_CLOSED); // pageListeners.firePageClosed(page); // partService.pageClosed(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } // //} // ///** // * Fires page opened // */ //void WorkbenchWindow::FirePageOpened(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "opened " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_OPENED); // pageListeners.firePageOpened(page); // partService.pageOpened(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } //} void WorkbenchWindow::FirePerspectiveActivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_ACTIVATED); perspectiveEvents.perspectiveActivated(page, perspective); } void WorkbenchWindow::FirePerspectivePreDeactivate( IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_PRE_DEACTIVATE); perspectiveEvents.perspectivePreDeactivate(page, perspective); } void WorkbenchWindow::FirePerspectiveDeactivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_DEACTIVATED); perspectiveEvents.perspectiveDeactivated(page, perspective); } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, null, changeId); perspectiveEvents.perspectiveChanged(page, perspective, changeId); } } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, partRef, changeId); perspectiveEvents.perspectivePartChanged(page, perspective, partRef, changeId); } } void WorkbenchWindow::FirePerspectiveClosed(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_CLOSED); perspectiveEvents.perspectiveClosed(page, perspective); } void WorkbenchWindow::FirePerspectiveOpened(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_OPENED); perspectiveEvents.perspectiveOpened(page, perspective); } void WorkbenchWindow::FirePerspectiveSavedAs(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer oldPerspective, IPerspectiveDescriptor::Pointer newPerspective) { // UIListenerLogging.logPerspectiveSavedAs(this, page, oldPerspective, // newPerspective); perspectiveEvents.perspectiveSavedAs(page, oldPerspective, newPerspective); } void WorkbenchWindow::FillActionBars(ActionBarAdvisor::FillFlags flags) { // Workbench workbench = getWorkbenchImpl(); // workbench.largeUpdateStart(); //try { this->GetActionBarAdvisor()->FillActionBars(flags); IMenuService* menuService = serviceLocator->GetService(); menuService->PopulateContributionManager(dynamic_cast(GetActionBars()->GetMenuManager()), MenuUtil::MAIN_MENU); // ICoolBarManager coolbar = getActionBars().getCoolBarManager(); // if (coolbar != null) // { // menuService.populateContributionManager( // (ContributionManager) coolbar, // MenuUtil.MAIN_TOOLBAR); // } // } finally { // workbench.largeUpdateEnd(); // } } -Point WorkbenchWindow::GetInitialSize() +QPoint WorkbenchWindow::GetInitialSize() { return this->GetWindowConfigurer()->GetInitialSize(); } bool WorkbenchWindow::Close() { //BERRY_INFO << "WorkbenchWindow::Close()"; if (controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(GetShell()->GetControl(), controlResizeListener); } bool ret = false; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(); // } // }); if (!ret && controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(GetShell()->GetControl(), controlResizeListener); } return ret; } bool WorkbenchWindow::BusyClose() { // Whether the window was actually closed or not bool windowClosed = false; // Setup internal flags to indicate window is in // progress of closing and no update should be done. closing = true; updateDisabled = true; try { // Only do the check if it is OK to close if we are not closing // via the workbench as the workbench will check this itself. Workbench* workbench = this->GetWorkbenchImpl(); std::size_t count = workbench->GetWorkbenchWindowCount(); // also check for starting - if the first window dies on startup // then we'll need to open a default window. if (!workbench->IsStarting() && !workbench->IsClosing() && count <= 1 && workbench->GetWorkbenchConfigurer() ->GetExitOnLastWindowClose()) { windowClosed = workbench->Close(); } else { if (this->OkToClose()) { windowClosed = this->HardClose(); } } } catch (std::exception& exc) { if (!windowClosed) { // Reset the internal flags if window was not closed. closing = false; updateDisabled = false; } throw exc; } // if (windowClosed && tracker != null) { // tracker.close(); // } return windowClosed; } void WorkbenchWindow::MakeVisible() { Shell::Pointer shell = GetShell(); if (shell) { // see bug 96700 and bug 4414 for a discussion on the use of open() // here shell->Open(); } } bool WorkbenchWindow::OkToClose() { // Save all of the editors. if (!this->GetWorkbenchImpl()->IsClosing()) { if (!this->SaveAllPages(true)) { return false; } } return true; } bool WorkbenchWindow::SaveAllPages(bool bConfirm) { bool bRet = true; PageList::iterator itr = pageList.Begin(); while (bRet && itr != pageList.End()) { bRet = (*itr)->SaveAllEditors(bConfirm); ++itr; } return bRet; } bool WorkbenchWindow::HardClose() { std::exception exc; bool exceptionOccured = false; try { // Clear the action sets, fix for bug 27416. //getActionPresentation().clearActionSets(); // Remove the handler submissions. Bug 64024. /* final IWorkbench workbench = getWorkbench(); final IHandlerService handlerService = (IHandlerService) workbench.getService(IHandlerService.class); handlerService.deactivateHandlers(handlerActivations); final Iterator activationItr = handlerActivations.iterator(); while (activationItr.hasNext()) { final IHandlerActivation activation = (IHandlerActivation) activationItr .next(); activation.getHandler().dispose(); } handlerActivations.clear(); globalActionHandlersByCommandId.clear(); */ // Remove the enabled submissions. Bug 64024. /* final IContextService contextService = (IContextService) workbench.getService(IContextService.class); contextService.unregisterShell(getShell()); */ this->CloseAllPages(); this->FireWindowClosed(); // time to wipe out our populate /* IMenuService menuService = (IMenuService) workbench .getService(IMenuService.class); menuService .releaseContributions(((ContributionManager) getActionBars() .getMenuManager())); ICoolBarManager coolbar = getActionBars().getCoolBarManager(); if (coolbar != null) { menuService .releaseContributions(((ContributionManager) coolbar)); } */ //getActionBarAdvisor().dispose(); //getWindowAdvisor().dispose(); //detachedWindowShells.dispose(); delete windowAdvisor; windowAdvisor = 0; // Null out the progress region. Bug 64024. //progressRegion = null; // Remove drop targets /* DragUtil.removeDragTarget(null, trimDropTarget); DragUtil.removeDragTarget(getShell(), trimDropTarget); trimDropTarget = null; if (trimMgr2 != null) { trimMgr2.dispose(); trimMgr2 = null; } if (trimContributionMgr != null) { trimContributionMgr.dispose(); trimContributionMgr = null; } */ } catch (std::exception& e) { exc = e; exceptionOccured = true; } bool result = Window::Close(); // Bring down all of the services ... after the window goes away serviceLocator->Dispose(); //menuRestrictions.clear(); if (exceptionOccured) throw exc; return result; } void WorkbenchWindow::CloseAllPages() { // Deactivate active page. this->SetActivePage(IWorkbenchPage::Pointer(0)); // Clone and deref all so that calls to getPages() returns // empty list (if called by pageClosed event handlers) PageList oldList = pageList; pageList.Clear(); // Close all. for (PageList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { partService.PageClosed(*itr); //(*itr)->FirePageClosed(page); //page.dispose(); } if (!closing) { this->ShowEmptyWindowContents(); } } WWinActionBars* WorkbenchWindow::GetActionBars() { if (actionBars.IsNull()) { actionBars = new WWinActionBars(this); } return actionBars.GetPointer(); } void WorkbenchWindow::SetPerspectiveExcludeList(const QStringList& v) { perspectiveExcludeList = v; } QStringList WorkbenchWindow::GetPerspectiveExcludeList() const { return perspectiveExcludeList; } void WorkbenchWindow::SetViewExcludeList(const QStringList& v) { viewExcludeList = v; } QStringList WorkbenchWindow::GetViewExcludeList() const { return viewExcludeList; } IWorkbenchPage::Pointer WorkbenchWindow::GetPage(int i) const { QList pages = pageList.GetPages(); int j = 0; for (auto it = pages.begin(); it!=pages.end(); it++, j++) { if (j==i) { return *it; } } return IWorkbenchPage::Pointer(); } IWorkbenchPage::Pointer WorkbenchWindow::GetActivePage() const { return pageList.GetActive(); } IWorkbench* WorkbenchWindow::GetWorkbench() { return PlatformUI::GetWorkbench(); } IPartService* WorkbenchWindow::GetPartService() { return &partService; } ISelectionService* WorkbenchWindow::GetSelectionService() { return partService.GetSelectionService(); } bool WorkbenchWindow::GetToolBarVisible() const { return GetWindowConfigurer()->GetShowToolBar() && toolBarVisible; } bool WorkbenchWindow::GetPerspectiveBarVisible() const { return GetWindowConfigurer()->GetShowPerspectiveBar() && perspectiveBarVisible; } bool WorkbenchWindow::GetStatusLineVisible() const { return GetWindowConfigurer()->GetShowStatusLine() && statusLineVisible; } void WorkbenchWindow::AddPropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.AddListener(listener); } void WorkbenchWindow::RemovePropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.RemoveListener(listener); } bool WorkbenchWindow::IsClosing() { return closing || this->GetWorkbenchImpl()->IsClosing(); } int WorkbenchWindow::Open() { if (pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } this->FireWindowCreated(); this->GetWindowAdvisor()->OpenIntro(); int result = Window::Open(); // It's time for a layout ... to insure that if TrimLayout // is in play, it updates all of the trim it's responsible // for. We have to do this before updating in order to get // the PerspectiveBar management correct...see defect 137334 //getShell().layout(); this->FireWindowOpened(); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.updatePerspectiveBar(); // perspectiveSwitcher.updateBarParent(); // } return result; } void* WorkbenchWindow::GetPageComposite() { return pageComposite; } QWidget *WorkbenchWindow::CreatePageComposite(QWidget *parent) { QtControlWidget* pageArea = new QtControlWidget(parent, 0); pageArea->setObjectName("Page Composite"); new QHBoxLayout(pageArea); if (qobject_cast (parent) != 0) qobject_cast (parent)->setCentralWidget(pageArea); else parent->layout()->addWidget(pageArea); // we have to enable visibility to get a proper layout (see bug #1654) pageArea->setVisible(true); parent->setVisible(true); pageComposite = pageArea; return pageArea; } void* WorkbenchWindow::CreateContents(Shell::Pointer parent) { // we know from Window.create that the parent is a Shell. this->GetWindowAdvisor()->CreateWindowContents(parent); // the page composite must be set by createWindowContents poco_assert(pageComposite != 0) ; // "createWindowContents must call configurer.createPageComposite"); //$NON-NLS-1$ return pageComposite; } void WorkbenchWindow::CreateDefaultContents(Shell::Pointer shell) { QMainWindow* mainWindow = qobject_cast(shell->GetControl()); if (GetWindowConfigurer()->GetShowMenuBar() && mainWindow) { QMenuBar* menuBar = GetMenuBarManager()->CreateMenuBar(mainWindow); mainWindow->setMenuBar(menuBar); } if (GetWindowConfigurer()->GetShowPerspectiveBar() && mainWindow) { mainWindow->addToolBar(new QtPerspectiveSwitcher(IWorkbenchWindow::Pointer(this))); } // Create the client composite area (where page content goes). CreatePageComposite(shell->GetControl()); } void WorkbenchWindow::CreateTrimWidgets(SmartPointer /*shell*/) { // do nothing -- trim widgets are created in CreateDefaultContents } bool WorkbenchWindow::UnableToRestorePage(IMemento::Pointer pageMem) { QString pageName; pageMem->GetString(WorkbenchConstants::TAG_LABEL, pageName); // return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.WorkbenchWindow_unableToRestorePerspective, // pageName), null); WorkbenchPlugin::Log("Unable to restore perspective: " + pageName); return false; } bool WorkbenchWindow::RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor) { //TODO WorkbenchWindow restore state poco_assert(GetShell()); // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsRestoringWindow, null); bool result = true; // Restore the window advisor state. IMemento::Pointer windowAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); if (windowAdvisorState) { //result.add(getWindowAdvisor().restoreState(windowAdvisorState)); result &= GetWindowAdvisor()->RestoreState(windowAdvisorState); } // Restore actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); if (actionBarAdvisorState) { // result.add(getActionBarAdvisor() // .restoreState(actionBarAdvisorState)); result &= GetActionBarAdvisor() ->RestoreState(actionBarAdvisorState); } // Read window's bounds and state. - Rectangle displayBounds; + QRect displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); - Rectangle shellBounds; // final IMemento fastViewMem = memento // .getChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewMem != null) { // if (fastViewBar != null) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // fastViewBar.restoreState(fastViewMem); // }}); // // } // } - memento->GetInteger(WorkbenchConstants::TAG_X, shellBounds.x); - memento->GetInteger(WorkbenchConstants::TAG_Y, shellBounds.y); - memento->GetInteger(WorkbenchConstants::TAG_WIDTH, shellBounds.width); - memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, shellBounds.height); - if (!shellBounds.IsEmpty()) + int x, y, w, h; + memento->GetInteger(WorkbenchConstants::TAG_X, x); + memento->GetInteger(WorkbenchConstants::TAG_Y, y); + memento->GetInteger(WorkbenchConstants::TAG_WIDTH, w); + memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, h); + QRect shellBounds(x, y, w, h); + + if (!shellBounds.isEmpty()) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { - if (!shellBounds.Intersects(displayBounds)) + if (!shellBounds.intersects(displayBounds)) { - Rectangle clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); - shellBounds.x = clientArea.x; - shellBounds.y = clientArea.y; + QRect clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); + shellBounds.setX(clientArea.x()); + shellBounds.setY(clientArea.y()); } GetShell()->SetBounds(shellBounds); // }}); } QString maximized; memento->GetString(WorkbenchConstants::TAG_MAXIMIZED, maximized); if (maximized == "true") { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { GetShell()->SetMaximized(true); // }}); } QString minimized; memento->GetString(WorkbenchConstants::TAG_MINIMIZED, minimized); if (minimized == "true") { // getShell().setMinimized(true); } // // restore the width of the perspective bar // if (perspectiveSwitcher != null) { // perspectiveSwitcher.restoreState(memento); // } // // Restore the cool bar order by creating all the tool bar contribution // // items // // This needs to be done before pages are created to ensure proper // // canonical creation // // of cool items // final ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // IMemento coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMem != null) { // // Check if the layout is locked // final Integer lockedInt = coolBarMem // .getInteger(IWorkbenchConstants.TAG_LOCKED); // StartupThreading.runWithoutExceptions(new StartupRunnable(){ // // public void runWithException() { // if ((lockedInt != null) && (lockedInt.intValue() == 1)) { // coolBarMgr.setLockLayout(true); // } else { // coolBarMgr.setLockLayout(false); // } // }}); // // // The new layout of the cool bar manager // ArrayList coolBarLayout = new ArrayList(); // // Traverse through all the cool item in the memento // IMemento contributionMems[] = coolBarMem // .getChildren(IWorkbenchConstants.TAG_COOLITEM); // for (int i = 0; i < contributionMems.length; i++) { // IMemento contributionMem = contributionMems[i]; // String type = contributionMem // .getString(IWorkbenchConstants.TAG_ITEM_TYPE); // if (type == null) { // // Do not recognize that type // continue; // } // String id = contributionMem // .getString(IWorkbenchConstants.TAG_ID); // // // Prevent duplicate items from being read back in. // IContributionItem existingItem = coolBarMgr.find(id); // if ((id != null) && (existingItem != null)) { // if (Policy.DEBUG_TOOLBAR_DISPOSAL) { // System.out // .println("Not loading duplicate cool bar item: " + id); //$NON-NLS-1$ // } // coolBarLayout.add(existingItem); // continue; // } // IContributionItem newItem = null; // if (type.equals(IWorkbenchConstants.TAG_TYPE_SEPARATOR)) { // if (id != null) { // newItem = new Separator(id); // } else { // newItem = new Separator(); // } // } else if (id != null) { // if (type // .equals(IWorkbenchConstants.TAG_TYPE_GROUPMARKER)) { // newItem = new GroupMarker(id); // // } else if (type // .equals(IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION) // || type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // // // Get Width and height // Integer width = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_X); // Integer height = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_Y); // // Look for the object in the current cool bar // // manager // IContributionItem oldItem = coolBarMgr.find(id); // // If a tool bar contribution item already exists // // for this id then use the old object // if (oldItem != null) { // newItem = oldItem; // } else { // IActionBarPresentationFactory actionBarPresentation = getActionBarPresentationFactory(); // newItem = actionBarPresentation.createToolBarContributionItem( // actionBarPresentation.createToolBarManager(), id); // if (type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // IToolBarContributionItem newToolBarItem = (IToolBarContributionItem) newItem; // if (height != null) { // newToolBarItem.setCurrentHeight(height // .intValue()); // } // if (width != null) { // newToolBarItem.setCurrentWidth(width // .intValue()); // } // newItem = new PlaceholderContributionItem( // newToolBarItem); // } // // make it invisible by default // newItem.setVisible(false); // // Need to add the item to the cool bar manager // // so that its canonical order can be preserved // IContributionItem refItem = findAlphabeticalOrder( // IWorkbenchActionConstants.MB_ADDITIONS, // id, coolBarMgr); // if (refItem != null) { // coolBarMgr.insertAfter(refItem.getId(), // newItem); // } else { // coolBarMgr.add(newItem); // } // } // // Set the current height and width // if ((width != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentWidth(width.intValue()); // } // if ((height != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentHeight(height.intValue()); // } // } // } // // Add new item into cool bar manager // if (newItem != null) { // coolBarLayout.add(newItem); // newItem.setParent(coolBarMgr); // coolBarMgr.markDirty(); // } // } // // // We need to check if we have everything we need in the layout. // boolean newlyAddedItems = false; // IContributionItem[] existingItems = coolBarMgr.getItems(); // for (int i = 0; i < existingItems.length && !newlyAddedItems; i++) { // IContributionItem existingItem = existingItems[i]; // // /* // * This line shouldn't be necessary, but is here for // * robustness. // */ // if (existingItem == null) { // continue; // } // // boolean found = false; // Iterator layoutItemItr = coolBarLayout.iterator(); // while (layoutItemItr.hasNext()) { // IContributionItem layoutItem = (IContributionItem) layoutItemItr // .next(); // if ((layoutItem != null) // && (layoutItem.equals(existingItem))) { // found = true; // break; // } // } // // if (!found) { // if (existingItem != null) { // newlyAddedItems = true; // } // } // } // // // Set the cool bar layout to the given layout. // if (!newlyAddedItems) { // final IContributionItem[] itemsToSet = new IContributionItem[coolBarLayout // .size()]; // coolBarLayout.toArray(itemsToSet); // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // coolBarMgr.setItems(itemsToSet); // } // }); // } // // } else { // // For older workbenchs // coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_TOOLBAR_LAYOUT); // if (coolBarMem != null) { // // Restore an older layout // restoreOldCoolBar(coolBarMem); // } // } // } // Recreate each page in the window. IWorkbenchPage::Pointer newActivePage; QList pageArray = memento ->GetChildren(WorkbenchConstants::TAG_PAGE); for (int i = 0; i < pageArray.size(); i++) { IMemento::Pointer pageMem = pageArray[i]; QString strFocus; pageMem->GetString(WorkbenchConstants::TAG_FOCUS, strFocus); if (strFocus.isEmpty()) { continue; } // Get the input factory. IAdaptable* input = 0; IMemento::Pointer inputMem = pageMem->GetChild(WorkbenchConstants::TAG_INPUT); if (inputMem) { QString factoryID; inputMem->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryID); if (factoryID.isEmpty()) { WorkbenchPlugin ::Log("Unable to restore page - no input factory ID."); //result.add(unableToRestorePage(pageMem)); result &= UnableToRestorePage(pageMem); continue; } // try { // UIStats.start(UIStats.RESTORE_WORKBENCH, // "WorkbenchPageFactory"); //$NON-NLS-1$ // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // IElementFactory factory = PlatformUI // .getWorkbench().getElementFactory( // factoryID); // if (factory == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input factory: " + factoryID); //$NON-NLS-1$ // result // .add(unableToRestorePage(pageMem)); // return; // } // // // Get the input element. // input[0] = factory.createElement(inputMem); // } // }); // // if (input[0] == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input element: " + factoryID); //$NON-NLS-1$ // result.add(unableToRestorePage(pageMem)); // continue; // } // } finally { // UIStats.end(UIStats.RESTORE_WORKBENCH, factoryID, // "WorkbenchPageFactory"); //$NON-NLS-1$ // } } // Open the perspective. IAdaptable* finalInput = input; WorkbenchPage::Pointer newPage; try { // StartupThreading.runWithWorkbenchExceptions(new StartupRunnable(){ // // public void runWithException() throws WorkbenchException { newPage = new WorkbenchPage(this, finalInput); // }}); //result.add(newPage[0].restoreState(pageMem, activeDescriptor)); result &= newPage->RestoreState(pageMem, activeDescriptor); pageList.Add(newPage); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { partService.PageOpened(newPage); // firePageOpened(newPage[0]); // }}); } catch (const WorkbenchException& e) { WorkbenchPlugin::Log( "Unable to restore perspective - constructor failed.", e); //$NON-NLS-1$ //result.add(e.getStatus()); continue; } if (!strFocus.isEmpty()) { newActivePage = newPage; } } // If there are no pages create a default. if (pageList.IsEmpty()) { try { const QString defPerspID = this->GetWorkbenchImpl()->GetPerspectiveRegistry() ->GetDefaultPerspective(); if (!defPerspID.isEmpty()) { WorkbenchPage::Pointer newPage; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newPage = new WorkbenchPage(this, defPerspID, this->GetDefaultPageInput()); // }}); pageList.Add(newPage); //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // firePageOpened(newPage[0]); partService.PageOpened(newPage); // }}); } } catch (WorkbenchException& e) { WorkbenchPlugin ::Log( "Unable to create default perspective - constructor failed.", e); result = false; //TODO set product name // String productName = WorkbenchPlugin.getDefault() // .getProductName(); // if (productName == null) { // productName = ""; //$NON-NLS-1$ // } // getShell().setText(productName); } } // Set active page. if (newActivePage.IsNull()) { newActivePage = pageList.GetNextActive().Cast(); } //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->SetActivePage(newActivePage); // }}); IMemento::Pointer introMem = memento->GetChild(WorkbenchConstants::TAG_INTRO); if (introMem) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { bool isStandby = false; introMem->GetBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); GetWorkbench()->GetIntroManager()->ShowIntro( IWorkbenchWindow::Pointer(this), isStandby); // } // }); } // // // Only restore the trim state if we're using the default layout // if (defaultLayout != null) { // // Restore the trim state. We pass in the 'root' // // memento since we have to check for pre-3.2 // // state. // result.add(restoreTrimState(memento)); // } return result; } IAdaptable* WorkbenchWindow::GetDefaultPageInput() { return this->GetWorkbenchImpl()->GetDefaultPageInput(); } IWorkbenchPage::Pointer WorkbenchWindow::OpenPage( const QString& perspId, IAdaptable* input) { // Run op in busy cursor. IWorkbenchPage::Pointer result; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { result = this->BusyOpenPage(perspId, input); // } return result; } SmartPointer WorkbenchWindow::OpenPage(IAdaptable* input) { QString perspId = this->GetWorkbenchImpl()->GetDefaultPerspectiveId(); return this->OpenPage(perspId, input); } IWorkbenchPage::Pointer WorkbenchWindow::BusyOpenPage( const QString& perspID, IAdaptable* input) { IWorkbenchPage::Pointer newPage; if (pageList.IsEmpty()) { newPage = new WorkbenchPage(this, perspID, input); pageList.Add(newPage); //this->FirePageOpened(newPage); partService.PageOpened(newPage); this->SetActivePage(newPage); } else { IWorkbenchWindow::Pointer window = this->GetWorkbench()->OpenWorkbenchWindow(perspID, input); newPage = window->GetActivePage(); } return newPage; } int WorkbenchWindow::GetNumber() { return number; } void WorkbenchWindow::UpdateActionBars() { if (updateDisabled || UpdatesDeferred()) { return; } // updateAll required in order to enable accelerators on pull-down menus GetMenuBarManager()->Update(false); //GetToolBarManager()->Update(false); //GetStatusLineManager()->Update(false); } void WorkbenchWindow::LargeUpdateStart() { largeUpdates++; } void WorkbenchWindow::LargeUpdateEnd() { if (--largeUpdates == 0) { this->UpdateActionBars(); } } void WorkbenchWindow::SetActivePage(IWorkbenchPage::Pointer in) { if (this->GetActivePage() == in) { return; } // 1FVGTNR: ITPUI:WINNT - busy cursor for switching perspectives //BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { // public void run() { // Deactivate old persp. WorkbenchPage::Pointer currentPage = pageList.GetActive(); if (currentPage.IsNotNull()) { currentPage->OnDeactivate(); } // Activate new persp. if (in.IsNull() || pageList.Contains(in)) { pageList.SetActive(in); } WorkbenchPage::Pointer newPage = pageList.GetActive(); //Composite parent = getPageComposite(); //StackLayout layout = (StackLayout) parent.getLayout(); if (newPage.IsNotNull()) { //layout.topControl = newPage.getClientComposite(); //parent.layout(); this->HideEmptyWindowContents(); newPage->OnActivate(); //this->FirePageActivated(newPage); partService.PageActivated(newPage); //TODO perspective if (newPage->GetPerspective() != 0) { this->FirePerspectiveActivated(newPage, newPage->GetPerspective()); } } else { //layout.topControl = null; //parent.layout(); } //updateFastViewBar(); if (this->IsClosing()) { return; } updateDisabled = false; // Update action bars ( implicitly calls updateActionBars() ) //updateActionSets(); //submitGlobalActions(); //if (perspectiveSwitcher != null) { // perspectiveSwitcher.update(false); //} //getMenuManager().update(IAction.TEXT); // } //}); } MenuManager *WorkbenchWindow::GetMenuManager() const { return this->GetMenuBarManager(); } bool WorkbenchWindow::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsSavingWindow, null); bool result = true; // Save the window's state and bounds. if (GetShell()->GetMaximized() || asMaximizedState) { memento->PutString(WorkbenchConstants::TAG_MAXIMIZED, "true"); } if (GetShell()->GetMinimized()) { memento->PutString(WorkbenchConstants::TAG_MINIMIZED, "true"); } - if (normalBounds.IsEmpty()) + if (normalBounds.isEmpty()) { normalBounds = GetShell()->GetBounds(); } // IMemento fastViewBarMem = memento // .createChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewBar != null) { // fastViewBar.saveState(fastViewBarMem); // } - memento->PutInteger(WorkbenchConstants::TAG_X, normalBounds.x); - memento->PutInteger(WorkbenchConstants::TAG_Y, normalBounds.y); - memento->PutInteger(WorkbenchConstants::TAG_WIDTH, normalBounds.width); - memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, normalBounds.height); + memento->PutInteger(WorkbenchConstants::TAG_X, normalBounds.x()); + memento->PutInteger(WorkbenchConstants::TAG_Y, normalBounds.y()); + memento->PutInteger(WorkbenchConstants::TAG_WIDTH, normalBounds.width()); + memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, normalBounds.height()); IWorkbenchPage::Pointer activePage = GetActivePage(); if (activePage && activePage->FindView(IntroConstants::INTRO_VIEW_ID)) { IMemento::Pointer introMem = memento ->CreateChild(WorkbenchConstants::TAG_INTRO); bool isStandby = GetWorkbench()->GetIntroManager() ->IsIntroStandby(GetWorkbench()->GetIntroManager()->GetIntro()); introMem->PutBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); } // // save the width of the perspective bar // IMemento persBarMem = memento // .createChild(IWorkbenchConstants.TAG_PERSPECTIVE_BAR); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.saveState(persBarMem); // } // // / Save the order of the cool bar contribution items // ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // coolBarMgr.refresh(); // IMemento coolBarMem = memento // .createChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMgr.getLockLayout() == true) { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 1); // } else { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 0); // } // IContributionItem[] items = coolBarMgr.getItems(); // for (int i = 0; i < items.length; i++) { // IMemento coolItemMem = coolBarMem // .createChild(IWorkbenchConstants.TAG_COOLITEM); // IContributionItem item = items[i]; // // The id of the contribution item // if (item.getId() != null) { // coolItemMem.putString(IWorkbenchConstants.TAG_ID, item // .getId()); // } // // Write out type and size if applicable // if (item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_SEPARATOR); // } else if (item.isGroupMarker() && !item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_GROUPMARKER); // } else { // if (item instanceof PlaceholderContributionItem) { // coolItemMem.putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_PLACEHOLDER); // } else { // // Store the identifier. // coolItemMem // .putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION); // } // // /* // * Retrieve a reasonable approximation of the height and // * width, if possible. // */ // final int height; // final int width; // if (item instanceof IToolBarContributionItem) { // IToolBarContributionItem toolBarItem = (IToolBarContributionItem) item; // toolBarItem.saveWidgetState(); // height = toolBarItem.getCurrentHeight(); // width = toolBarItem.getCurrentWidth(); // } else if (item instanceof PlaceholderContributionItem) { // PlaceholderContributionItem placeholder = (PlaceholderContributionItem) item; // height = placeholder.getHeight(); // width = placeholder.getWidth(); // } else { // height = -1; // width = -1; // } // // // Store the height and width. // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_X, // width); // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_Y, // height); // } // } // } // Save each page. for (PageList::iterator itr = pageList.Begin(); itr != pageList.End(); ++itr) { WorkbenchPage::Pointer page = itr->Cast(); // Save perspective. IMemento::Pointer pageMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); pageMem->PutString(WorkbenchConstants::TAG_LABEL, page->GetLabel()); //result.add(page.saveState(pageMem)); result &= page->SaveState(pageMem); if (page == GetActivePage().Cast()) { pageMem->PutString(WorkbenchConstants::TAG_FOCUS, "true"); } // // Get the input. // IAdaptable* input = page->GetInput(); // if (input != 0) { // IPersistableElement persistable = (IPersistableElement) Util.getAdapter(input, // IPersistableElement.class); // if (persistable == null) { // WorkbenchPlugin // .log("Unable to save page input: " //$NON-NLS-1$ // + input // + ", because it does not adapt to IPersistableElement"); //$NON-NLS-1$ // } else { // // Save input. // IMemento inputMem = pageMem // .createChild(IWorkbenchConstants.TAG_INPUT); // inputMem.putString(IWorkbenchConstants.TAG_FACTORY_ID, // persistable.getFactoryId()); // persistable.saveState(inputMem); // } // } } // Save window advisor state. IMemento::Pointer windowAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); //result.add(getWindowAdvisor().saveState(windowAdvisorState)); result &= GetWindowAdvisor()->SaveState(windowAdvisorState); // Save actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); //result.add(getActionBarAdvisor().saveState(actionBarAdvisorState)); result &= GetActionBarAdvisor()->SaveState(actionBarAdvisorState); // // Only save the trim state if we're using the default layout // if (defaultLayout != null) { // IMemento trimState = memento.createChild(IWorkbenchConstants.TAG_TRIM); // result.add(saveTrimState(trimState)); // } return result; } WorkbenchWindowConfigurer::Pointer WorkbenchWindow::GetWindowConfigurer() const { if (windowConfigurer.IsNull()) { // lazy initialize windowConfigurer = new WorkbenchWindowConfigurer(WorkbenchWindow::Pointer(const_cast(this))); } return windowConfigurer; } bool WorkbenchWindow::CanHandleShellCloseEvent() { if (!Window::CanHandleShellCloseEvent()) { return false; } // let the advisor or other interested parties // veto the user's explicit request to close the window return FireWindowShellClosing(); } void WorkbenchWindow::ConfigureShell(Shell::Pointer shell) { Window::ConfigureShell(shell); detachedWindowShells = new ShellPool(shell, Constants::TITLE | Constants::MAX | Constants::CLOSE | Constants::RESIZE | Constants::BORDER ); QString title = this->GetWindowConfigurer()->BasicGetTitle(); if (!title.isEmpty()) { shell->SetText(title); } // final IWorkbench workbench = getWorkbench(); // workbench.getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.WORKBENCH_WINDOW); // final IContextService contextService = (IContextService) getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); this->TrackShellActivation(shell); this->TrackShellResize(shell); } ShellPool::Pointer WorkbenchWindow::GetDetachedWindowPool() { return detachedWindowShells; } WorkbenchAdvisor* WorkbenchWindow::GetAdvisor() { return this->GetWorkbenchImpl()->GetAdvisor(); } WorkbenchWindowAdvisor* WorkbenchWindow::GetWindowAdvisor() { if (windowAdvisor == 0) { windowAdvisor = this->GetAdvisor()->CreateWorkbenchWindowAdvisor(this->GetWindowConfigurer()); poco_check_ptr(windowAdvisor); } return windowAdvisor; } ActionBarAdvisor::Pointer WorkbenchWindow::GetActionBarAdvisor() { if (actionBarAdvisor.IsNull()) { actionBarAdvisor = this->GetWindowAdvisor()->CreateActionBarAdvisor(this->GetWindowConfigurer()->GetActionBarConfigurer()); poco_assert(actionBarAdvisor.IsNotNull()); } return actionBarAdvisor; } Workbench* WorkbenchWindow::GetWorkbenchImpl() { return dynamic_cast(this->GetWorkbench()); } void WorkbenchWindow::ShowEmptyWindowContents() { if (!emptyWindowContentsCreated) { void* parent = this->GetPageComposite(); emptyWindowContents = this->GetWindowAdvisor()->CreateEmptyWindowContents( parent); emptyWindowContentsCreated = true; // // force the empty window composite to be layed out // ((StackLayout) parent.getLayout()).topControl = emptyWindowContents; // parent.layout(); } } void WorkbenchWindow::HideEmptyWindowContents() { if (emptyWindowContentsCreated) { if (emptyWindowContents != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(emptyWindowContents); emptyWindowContents = 0; //this->GetPageComposite().layout(); } emptyWindowContentsCreated = false; } } WorkbenchWindow::ServiceLocatorOwner::ServiceLocatorOwner(WorkbenchWindow* wnd) : window(wnd) { } void WorkbenchWindow::ServiceLocatorOwner::Dispose() { Shell::Pointer shell = window->GetShell(); if (shell != 0) { window->Close(); } } bool WorkbenchWindow::PageList::Add(IWorkbenchPage::Pointer object) { pagesInCreationOrder.push_back(object); pagesInActivationOrder.push_front(object); // It will be moved to top only when activated. return true; } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::Begin() { return pagesInCreationOrder.begin(); } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::End() { return pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Contains(IWorkbenchPage::Pointer object) { return std::find(pagesInCreationOrder.begin(), pagesInCreationOrder.end(), object) != pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Remove(IWorkbenchPage::Pointer object) { if (active == object) { active = 0; } pagesInActivationOrder.removeAll(object); const int origSize = pagesInCreationOrder.size(); pagesInCreationOrder.removeAll(object); return origSize != pagesInCreationOrder.size(); } void WorkbenchWindow::PageList::Clear() { pagesInCreationOrder.clear(); pagesInActivationOrder.clear(); active = 0; } bool WorkbenchWindow::PageList::IsEmpty() { return pagesInCreationOrder.empty(); } QList WorkbenchWindow::PageList::GetPages() const { return pagesInCreationOrder; } void WorkbenchWindow::PageList::SetActive(IWorkbenchPage::Pointer page) { if (active == page) { return; } active = page; if (page.IsNotNull()) { pagesInActivationOrder.removeAll(page); pagesInActivationOrder.push_back(page); } } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetActive() const { return active.Cast(); } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetNextActive() { if (active.IsNull()) { if (pagesInActivationOrder.empty()) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.back().Cast(); } if (pagesInActivationOrder.size() < 2) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.at(pagesInActivationOrder.size()-2).Cast(); } WorkbenchWindow::ShellActivationListener::ShellActivationListener(WorkbenchWindow::Pointer w) : window(w) { } void WorkbenchWindow::ShellActivationListener::ShellActivated(const ShellEvent::Pointer& /*event*/) { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = true; wnd->serviceLocator->Activate(); wnd->GetWorkbenchImpl()->SetActivatedWindow(wnd); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellActivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellActivated(); } wnd->GetWorkbenchImpl()->FireWindowActivated(wnd); } //liftRestrictions(); } void WorkbenchWindow::ShellActivationListener::ShellDeactivated(const ShellEvent::Pointer& /*event*/) { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = false; //imposeRestrictions(); wnd->serviceLocator->Deactivate(); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } wnd->GetWorkbenchImpl()->FireWindowDeactivated(wnd); } } void WorkbenchWindow::TrackShellActivation(Shell::Pointer shell) { shellActivationListener.reset(new ShellActivationListener(WorkbenchWindow::Pointer(this))); shell->AddShellListener(shellActivationListener.data()); } WorkbenchWindow::ControlResizeListener::ControlResizeListener(WorkbenchWindow* w) : window(w) { } GuiTk::IControlListener::Events::Types WorkbenchWindow::ControlResizeListener::GetEventTypes() const { return Events::MOVED | Events::RESIZED; } void WorkbenchWindow:: ControlResizeListener::ControlMoved(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow:: ControlResizeListener::ControlResized(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow::ControlResizeListener::SaveBounds() { WorkbenchWindow::Pointer wnd(window); Shell::Pointer shell = wnd->GetShell(); if (shell == 0) { return; } // if (shell->IsDisposed()) // { // return; // } if (shell->GetMinimized()) { return; } if (shell->GetMaximized()) { wnd->asMaximizedState = true; return; } wnd->asMaximizedState = false; wnd->normalBounds = shell->GetBounds(); } void WorkbenchWindow::TrackShellResize(Shell::Pointer newShell) { controlResizeListener = new ControlResizeListener(this); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(newShell->GetControl(), controlResizeListener); } bool WorkbenchWindow::UpdatesDeferred() const { return largeUpdates > 0; } void WorkbenchWindow::InitializeDefaultServices() { workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WINDOW_SCOPE, GetWorkbench(), this, NULL, 1)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); //ActionCommandMappingService* mappingService = new ActionCommandMappingService(); //serviceLocator->RegisterService(IActionCommandMappingService, mappingService); } QSet > WorkbenchWindow::GetMenuRestrictions() const { return QSet >(); } void WorkbenchWindow::FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue) { PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue)); genericPropertyListeners.propertyChange(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h index 171df8b4ae..5517591391 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h @@ -1,738 +1,739 @@ /*=================================================================== 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 BERRYWORKBENCHWINDOW_H_ #define BERRYWORKBENCHWINDOW_H_ #include "berryIWorkbenchWindow.h" #include "berryIPerspectiveListener.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryWindow.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryShellPool.h" #include "berryServiceLocator.h" #include "berryWWinPartService.h" #include "application/berryWorkbenchAdvisor.h" #include "application/berryWorkbenchWindowAdvisor.h" #include "application/berryActionBarAdvisor.h" #include +#include namespace berry { struct IEvaluationReference; struct IWorkbench; struct IWorkbenchPage; struct IPartService; struct ISelectionService; struct IPerspectiveDescriptor; struct IWorkbenchLocationService; class Workbench; class WorkbenchPage; class WWinActionBars; /** * \ingroup org_blueberry_ui_qt * */ class BERRY_UI_QT WorkbenchWindow: public Window, public IWorkbenchWindow { public: /** * Toolbar visibility change property. */ static const QString PROP_TOOLBAR_VISIBLE; // = "toolbarVisible"; /** * Perspective bar visibility change property. */ static const QString PROP_PERSPECTIVEBAR_VISIBLE; // = "perspectiveBarVisible"; /** * The status line visibility change property. for internal use only. */ static const QString PROP_STATUS_LINE_VISIBLE; // = "statusLineVisible"; public: berryObjectMacro(WorkbenchWindow) WorkbenchWindow(int number); ~WorkbenchWindow(); Object* GetService(const QString& key); bool HasService(const QString& key) const; int Open(); bool Close(); Shell::Pointer GetShell() const; /** * @see org.blueberry.ui.IPageService */ void AddPerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ void RemovePerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ IPerspectiveListener::Events& GetPerspectiveEvents(); /** * Returns the action bars for this window. */ WWinActionBars* GetActionBars(); SmartPointer GetActivePage() const; SmartPointer GetPage(int i) const; void SetPerspectiveExcludeList(const QStringList& v); QStringList GetPerspectiveExcludeList() const; void SetViewExcludeList(const QStringList& v); QStringList GetViewExcludeList() const; /** * Sets the active page within the window. * * @param in * identifies the new active page, or null for no * active page */ void SetActivePage(SmartPointer in); /** * Answer the menu manager for this window. */ MenuManager* GetMenuManager() const; IWorkbench* GetWorkbench(); IPartService* GetPartService(); ISelectionService* GetSelectionService(); /** * @return whether the tool bar should be shown. This is only applicable if * the window configurer also wishes the cool bar to be visible. */ bool GetToolBarVisible() const; /** * @return whether the perspective bar should be shown. This is only * applicable if the window configurer also wishes the perspective * bar to be visible. */ bool GetPerspectiveBarVisible() const; /** * @return whether the status line should be shown. This is only applicable if * the window configurer also wishes status line to be visible. */ bool GetStatusLineVisible() const; /** * Add a generic property listener. * * @param listener the listener to add */ void AddPropertyChangeListener(IPropertyChangeListener* listener); /** * Removes a generic property listener. * * @param listener the listener to remove */ void RemovePropertyChangeListener(IPropertyChangeListener* listener); SmartPointer OpenPage(const QString& perspectiveId, IAdaptable* input); SmartPointer OpenPage(IAdaptable* input); //TODO menu manager //virtual void* GetMenuManager() = 0; virtual bool SaveState(IMemento::Pointer memento); /** * Called when this window is about to be closed. * * Subclasses may overide to add code that returns false to * prevent closing under certain conditions. */ virtual bool OkToClose(); bool RestoreState(IMemento::Pointer memento, SmartPointer< IPerspectiveDescriptor> activeDescriptor); /** * Returns the number. This corresponds to a page number in a window or a * window number in the workbench. */ int GetNumber(); /** * update the action bars. */ void UpdateActionBars(); /** *

    * Indicates the start of a large update within this window. This is used to * disable CPU-intensive, change-sensitive services that were temporarily * disabled in the midst of large changes. This method should always be * called in tandem with largeUpdateEnd, and the event loop * should not be allowed to spin before that method is called. *

    *

    * Important: always use with largeUpdateEnd! *

    * * @since 3.1 */ void LargeUpdateStart(); /** *

    * Indicates the end of a large update within this window. This is used to * re-enable services that were temporarily disabled in the midst of large * changes. This method should always be called in tandem with * largeUpdateStart, and the event loop should not be * allowed to spin before this method is called. *

    *

    * Important: always protect this call by using finally! *

    * * @since 3.1 */ void LargeUpdateEnd(); QSet > GetMenuRestrictions() const; protected: friend class WorkbenchConfigurer; friend class WorkbenchWindowConfigurer; friend class WorkbenchWindowConfigurer::WindowActionBarConfigurer; friend class Workbench; friend class LayoutPartSash; friend class EditorSashContainer; friend class WorkbenchPage; friend class DetachedWindow; /** * Returns the GUI dependent page composite, under which the window's * pages create their controls. */ void* GetPageComposite(); /** * Creates and remembers the client composite, under which workbench pages * create their controls. */ QWidget* CreatePageComposite(QWidget* parent); /** * Creates the contents of the workbench window, including trim controls and * the client composite. This MUST create the client composite via a call to * createClientComposite. * * @since 3.0 */ void* CreateContents(Shell::Pointer parent); /** * Creates the default contents and layout of the shell. * * @param shell * the shell */ virtual void CreateDefaultContents(Shell::Pointer shell); void CreateTrimWidgets(SmartPointer shell); /** * Returns the unique object that applications use to configure this window. *

    * IMPORTANT This method is declared package-private to prevent regular * plug-ins from downcasting IWorkbenchWindow to WorkbenchWindow and getting * hold of the workbench window configurer that would allow them to tamper * with the workbench window. The workbench window configurer is available * only to the application. *

    */ WorkbenchWindowConfigurer::Pointer GetWindowConfigurer() const; bool CanHandleShellCloseEvent(); /* * @see berry::Window#configureShell(Shell::Pointer) */ void ConfigureShell(Shell::Pointer shell); ShellPool::Pointer GetDetachedWindowPool(); /** * Fills the window's real action bars. * * @param flags * indicate which bars to fill */ void FillActionBars(ActionBarAdvisor::FillFlags flags); /** * The WorkbenchWindow implementation of this method * delegates to the window configurer. * * @since 3.0 */ - Point GetInitialSize(); + QPoint GetInitialSize(); /** * Returns the default page input for workbench pages opened in this window. * * @return the default page input or null if none * @since 3.1 */ IAdaptable* GetDefaultPageInput(); bool IsClosing(); /** * Opens a new page. Assumes that busy cursor is active. *

    * Note: Since release 2.0, a window is limited to contain at most * one page. If a page exist in the window when this method is used, then * another window is created for the new page. Callers are strongly * recommended to use the IWorkbench.openPerspective APIs to * programmatically show a perspective. *

    */ SmartPointer BusyOpenPage(const QString& perspID, IAdaptable* input); bool ClosePage(SmartPointer in, bool save); /** * Makes the window visible and frontmost. */ void MakeVisible(); /** * The composite under which workbench pages create their controls. */ QWidget* pageComposite; private: /** * Constant indicating that all the actions bars should be filled. * * @since 3.0 */ static const ActionBarAdvisor::FillFlags FILL_ALL_ACTION_BARS; ShellPool::Pointer detachedWindowShells; /** * Object for configuring this workbench window. Lazily initialized to an * instance unique to this window. * * @since 3.0 */ mutable WorkbenchWindowConfigurer::Pointer windowConfigurer; WorkbenchWindowAdvisor* windowAdvisor; ActionBarAdvisor::Pointer actionBarAdvisor; SmartPointer actionBars; IPropertyChangeListener::Events genericPropertyListeners; int number; /** * The number of large updates that are currently going on. If this is * number is greater than zero, then UI updateActionBars is a no-op. */ int largeUpdates; bool closing; bool shellActivated; bool updateDisabled; bool toolBarVisible; bool perspectiveBarVisible; bool statusLineVisible; /** * The map of services maintained by the workbench window. These services * are initialized during workbench window during the * {@link #configureShell(Shell)}. */ ServiceLocator::Pointer serviceLocator; QScopedPointer workbenchLocationService; bool emptyWindowContentsCreated; void* emptyWindowContents; - Rectangle normalBounds; + QRect normalBounds; bool asMaximizedState; IPerspectiveListener::Events perspectiveEvents; WWinPartService partService; QStringList perspectiveExcludeList; QStringList viewExcludeList; struct ServiceLocatorOwner: public IDisposable { ServiceLocatorOwner(WorkbenchWindow* wnd); WorkbenchWindow* window; void Dispose(); }; IDisposable::Pointer serviceLocatorOwner; class PageList { private: // List of pages in the order they were created; QList > pagesInCreationOrder; // List of pages where the top is the last activated. QList > pagesInActivationOrder; // The page explicitly activated SmartPointer active; public: typedef QList >::iterator iterator; bool Add(SmartPointer object); iterator Begin(); iterator End(); void Clear(); bool Contains(SmartPointer object); bool Remove(SmartPointer object); bool IsEmpty(); QList > GetPages() const; void SetActive(SmartPointer page); SmartPointer GetActive() const; SmartPointer GetNextActive(); }; PageList pageList; /** * Notifies interested parties (namely the advisor) that the window is about * to be opened. * * @since 3.1 */ void FireWindowOpening(); /** * Notifies interested parties (namely the advisor) that the window has been * restored from a previously saved state. * * @throws WorkbenchException * passed through from the advisor * @since 3.1 */ void FireWindowRestored(); /** * Notifies interested parties (namely the advisor) that the window has been * created. * * @since 3.1 */ void FireWindowCreated(); /** * Notifies interested parties (namely the advisor and the window listeners) * that the window has been opened. * * @since 3.1 */ void FireWindowOpened(); /** * Notifies interested parties (namely the advisor) that the window's shell * is closing. Allows the close to be vetoed. * * @return true if the close should proceed, * false if it should be canceled * @since 3.1 */ bool FireWindowShellClosing(); /** * Notifies interested parties (namely the advisor and the window listeners) * that the window has been closed. * * @since 3.1 */ void FireWindowClosed(); // /** // * Fires page activated // */ // void FirePageActivated(IWorkbenchPage::Pointer page); // // /** // * Fires page closed // */ // void FirePageClosed(IWorkbenchPage::Pointer page); // // /** // * Fires page opened // */ // void FirePageOpened(IWorkbenchPage::Pointer page); /** * Fires perspective activated */ void FirePerspectiveActivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective deactivated. * * @since 3.2 */ void FirePerspectivePreDeactivate(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective deactivated. * * @since 3.1 */ void FirePerspectiveDeactivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective changed */ void FirePerspectiveChanged(SmartPointer , IPerspectiveDescriptor::Pointer perspective, const QString& changeId); /** * Fires perspective changed for an affected part */ void FirePerspectiveChanged(SmartPointer , IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const QString& changeId); /** * Fires perspective closed */ void FirePerspectiveClosed(SmartPointer , IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective opened */ void FirePerspectiveOpened(SmartPointer , IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective saved as. * * @since 3.1 */ void FirePerspectiveSavedAs(SmartPointer , IPerspectiveDescriptor::Pointer oldPerspective, IPerspectiveDescriptor::Pointer newPerspective); /** * Returns the workbench advisor. Assumes the workbench has been created * already. *

    * IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the workbench advisor that would allow them to tamper with the workbench. * The workbench advisor is internal to the application. *

    */ /* private - DO NOT CHANGE */ WorkbenchAdvisor* GetAdvisor(); /** * Returns the window advisor, creating a new one for this window if needed. *

    * IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the window advisor that would allow them to tamper with the window. The * window advisor is internal to the application. *

    */ /* private - DO NOT CHANGE */ WorkbenchWindowAdvisor* GetWindowAdvisor(); /** * Returns the action bar advisor, creating a new one for this window if * needed. *

    * IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the action bar advisor that would allow them to tamper with the window's * action bars. The action bar advisor is internal to the application. *

    */ /* private - DO NOT CHANGE */ ActionBarAdvisor::Pointer GetActionBarAdvisor(); /* * Returns the IWorkbench implementation. */ Workbench* GetWorkbenchImpl(); bool UnableToRestorePage(IMemento::Pointer pageMem); /** * Close the window. * * Assumes that busy cursor is active. */ bool BusyClose(); /** * Unconditionally close this window. Assumes the proper flags have been set * correctly (e.i. closing and updateDisabled) */ bool HardClose(); /** * Close all of the pages. */ void CloseAllPages(); /** * Save all of the pages. Returns true if the operation succeeded. */ bool SaveAllPages(bool bConfirm); void ShowEmptyWindowContents(); void HideEmptyWindowContents(); struct ShellActivationListener: public IShellListener { ShellActivationListener(WorkbenchWindow::Pointer window); void ShellActivated(const ShellEvent::Pointer& event); void ShellDeactivated(const ShellEvent::Pointer& event); private: WorkbenchWindow::WeakPtr window; }; QScopedPointer shellActivationListener; /** * Hooks a listener to track the activation and deactivation of the window's * shell. Notifies the active part and editor of the change */ void TrackShellActivation(Shell::Pointer shell); struct ControlResizeListener: public GuiTk::IControlListener { ControlResizeListener(WorkbenchWindow* window); GuiTk::IControlListener::Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer e); void ControlResized(GuiTk::ControlEvent::Pointer e); private: void SaveBounds(); WorkbenchWindow* window; }; GuiTk::IControlListener::Pointer controlResizeListener; /** * Hooks a listener to track the resize of the window's shell. Stores the * new bounds if in normal state - that is, not in minimized or maximized * state) */ void TrackShellResize(Shell::Pointer newShell); /** * Returns true iff we are currently deferring UI processing due to a large * update * * @return true iff we are deferring UI updates. */ bool UpdatesDeferred() const; /** * Initializes all of the default command-based services for the workbench * window. */ void InitializeDefaultServices(); void FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue); }; } #endif /*BERRYWORKBENCHWINDOW_H_*/ 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 7800248421..b7c8858ca5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp @@ -1,295 +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 "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 +QPoint WorkbenchWindowConfigurer::GetInitialSize() const { return initialSize; } -void WorkbenchWindowConfigurer::SetInitialSize(Point size) +void WorkbenchWindowConfigurer::SetInitialSize(QPoint 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/berryWorkbenchWindowConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.h index 8cd53c38d8..e52bab1d82 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.h @@ -1,405 +1,406 @@ /*=================================================================== 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 BERRYWORKBENCHWINDOWCONFIGURER_H_ #define BERRYWORKBENCHWINDOWCONFIGURER_H_ #include "application/berryIActionBarConfigurer.h" #include "application/berryIWorkbenchConfigurer.h" #include "application/berryIWorkbenchWindowConfigurer.h" #include #include +#include class QToolBar; class QMenuBar; namespace berry { class WorkbenchWindow; /** * Internal class providing special access for configuring workbench windows. *

    * Note that these objects are only available to the main application * (the plug-in that creates and owns the workbench). *

    *

    * This class is not intended to be instantiated or subclassed by clients. *

    */ class WorkbenchWindowConfigurer : public IWorkbenchWindowConfigurer { friend class WorkbenchWindow; public: berryObjectMacro(WorkbenchWindowConfigurer) /** * Creates a new workbench window configurer. *

    * This method is declared package-private:. Clients obtain instances * via {@link WorkbenchAdvisor#getWindowConfigurer * WorkbenchAdvisor.getWindowConfigurer} *

    * * @param window the workbench window that this object configures * @see WorkbenchAdvisor#getWindowConfigurer */ WorkbenchWindowConfigurer(const SmartPointer& window); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getWindow */ SmartPointer GetWindow(); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getWorkbenchConfigurer() */ SmartPointer GetWorkbenchConfigurer(); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getTitle */ QString GetTitle(); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setTitle */ void SetTitle(const QString& title); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowMenuBar */ bool GetShowMenuBar() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setShowMenuBar */ void SetShowMenuBar(bool show); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowToolBar */ bool GetShowToolBar() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ void SetShowToolBar(bool show); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ bool GetShowPerspectiveBar() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ void SetShowPerspectiveBar(bool show); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowStatusLine */ bool GetShowStatusLine() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setShowStatusLine */ void SetShowStatusLine(bool show); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ bool GetShowProgressIndicator() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ void SetShowProgressIndicator(bool show); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getData */ // Object getData(String key) { // if (key == null) { // throw new IllegalArgumentException(); // } // return extraData.get(key); // } /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setData */ // void setData(String key, Object data) { // if (key == null) { // throw new IllegalArgumentException(); // } // if (data != null) { // extraData.put(key, data); // } else { // extraData.remove(key); // } // } /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#addEditorAreaTransfer */ void AddEditorAreaTransfer(const QStringList& transferTypes); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ void ConfigureEditorAreaDropListener(IDropTargetListener* listener); /** * Returns the array of Transfer added by the application */ QStringList GetTransfers() const; /** * Returns the drop listener provided by the application. */ IDropTargetListener* GetDropTargetListener() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ SmartPointer GetActionBarConfigurer(); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ Qt::WindowFlags GetWindowFlags() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ void SetWindowFlags(Qt::WindowFlags shellStyle); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ - Point GetInitialSize() const; + QPoint GetInitialSize() const; /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ - void SetInitialSize(Point size); + void SetInitialSize(QPoint size); /** * Creates the default window contents. * * @param shell the shell */ void CreateDefaultContents(SmartPointer shell); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ QMenuBar* CreateMenuBar(); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ QWidget* CreateToolBar(QWidget* parent); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ // public: Control createStatusLineControl(Composite parent) { // return window.getStatusLineManager().createControl(parent); // } /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ QWidget* CreatePageComposite(QWidget* parent); /* * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#saveState(org.blueberry.ui.IMemento) */ bool SaveState(SmartPointer memento); protected: /** * Returns the title as set by setTitle, without consulting the shell. * * @return the window title as set, or null if not set */ QString BasicGetTitle(); private: /** * Action bar configurer that changes this workbench window. * This implementation keeps track of tool bar items */ class WindowActionBarConfigurer : public IActionBarConfigurer { private: IActionBarConfigurer::Pointer proxy; WeakPointer window; public: berryObjectMacro(WindowActionBarConfigurer) WindowActionBarConfigurer(WeakPointer wnd); /** * Sets the proxy to use, or null for none. * * @param proxy the proxy */ void SetProxy(IActionBarConfigurer::Pointer proxy); /* * @see org.blueberry.ui.application.IActionBarConfigurer#getWindowConfigurer() */ IWorkbenchWindowConfigurer::Pointer GetWindowConfigurer(); /* * @see org.blueberry.ui.application.IActionBarConfigurer */ // public: IStatusLineManager getStatusLineManager() { // if (proxy != null) { // return proxy.getStatusLineManager(); // } // return window.getStatusLineManager(); // } /* * @see org.blueberry.ui.application.IActionBarConfigurer */ IMenuManager* GetMenuManager(); /* * @see org.blueberry.ui.internal.AbstractActionBarConfigurer */ IToolBarManager* GetToolBarManager(); /* * @see org.blueberry.ui.application.IActionBarConfigurer */ // public: void registerGlobalAction(IAction action) { // if (proxy != null) { // proxy.registerGlobalAction(action); // } // window.registerGlobalAction(action); // } /* * @see org.blueberry.ui.application.IActionBarConfigurer#createToolBarManager() */ // public: IToolBarManager createToolBarManager() { // if (proxy != null) { // return proxy.createToolBarManager(); // } // return getActionBarPresentationFactory().createToolBarManager(); // } }; /** * The workbench window associated with this configurer. */ WeakPointer window; /** * The shell style bits to use when the window's shell is being created. */ Qt::WindowFlags shellStyle; /** * The window title to set when the window's shell has been created. */ QString windowTitle; /* * Whether the workbench window should show the fast view bars. */ //bool showFastViewBars = false; /** * Whether the workbench window should show the perspective bar */ bool showPerspectiveBar; /** * Whether the workbench window should show the status line. */ bool showStatusLine; /** * Whether the workbench window should show the main tool bar. */ bool showToolBar; /** * Whether the workbench window should show the main menu bar. */ bool showMenuBar; /** * Whether the workbench window should have a progress indicator. */ bool showProgressIndicator; /* * Table to hold arbitrary key-data settings (key type: String, * value type: Object). * @see #setData */ //Map extraData = new HashMap(1); /** * Holds the list drag and drop Transfer for the * editor area */ QSet transferTypes; /** * The DropTargetListener implementation for handling a * drop into the editor area. */ IDropTargetListener* dropTargetListener; /** * The initial size to use for the shell. */ - Point initialSize; + QPoint initialSize; /** * Object for configuring this workbench window's action bars. * Lazily initialized to an instance unique to this window. */ SmartPointer actionBarConfigurer; }; } #endif /*BERRYWORKBENCHWINDOWCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp index 895a749dd5..20028c0038 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabFolder.cpp @@ -1,364 +1,363 @@ /*=================================================================== 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 "berryNativeTabFolder.h" #include "berryNativeTabItem.h" #include "berryQCTabBar.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace berry { AbstractTabItem* NativeTabFolder::GetTab(int index) { return tabControl->getTab(index); } void NativeTabFolder::TabSelectionChanged(int index) { this->FireEvent(TabFolderEvent::EVENT_TAB_SELECTED, tabControl->getTab(index)); } void NativeTabFolder::DragStarted(const QPoint& location) { - Point point(location.x(), location.y()); this->HandleDragStarted(location); } void NativeTabFolder::ViewFormDestroyed(QObject*) { viewForm = 0; content = 0; } NativeTabFolder::NativeTabFolder(QWidget* parent) : QObject(parent) { content = 0; viewForm = new QtControlWidget(parent, 0); viewForm->setObjectName("ViewForm"); viewForm->installEventFilter(this); QVBoxLayout* layout = new QVBoxLayout(viewForm); layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); viewForm->setLayout(layout); connect(viewForm, SIGNAL(destroyed(QObject*)), this, SLOT(ViewFormDestroyed(QObject*))); QWidget* topControls = new QWidget(viewForm); topControls->setMinimumSize(0, 24); topControls->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addWidget(topControls); QHBoxLayout* topLayout = new QHBoxLayout(topControls); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->setSpacing(0); tabControl = new QCTabBar(topControls); tabControl->installEventFilter(this); tabControl->setMinimumSize(0, 25); tabControl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); topLayout->addWidget(tabControl); QFrame* topRightControls = new QFrame(topControls); topRightControls->setObjectName("TabTopRightControls"); topRightControls->setMinimumSize(6, 25); topRightControls->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); topLayout->addWidget(topRightControls); contentFrame = new QFrame(viewForm); contentFrame->setObjectName("ViewFormContentFrame"); contentFrame->installEventFilter(this); contentFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout* contentFrameLayout = new QVBoxLayout(contentFrame); contentFrameLayout->setContentsMargins(0,0,0,0); contentFrameLayout->setSpacing(0); //contentFrame->setLayout(layout); layout->addWidget(contentFrame); this->connect(tabControl, SIGNAL(currentChanged(int)), this, SLOT(TabSelectionChanged(int))); this->connect(tabControl, SIGNAL(dragStarted(const QPoint&)), this, SLOT(DragStarted(const QPoint&))); //std::cout << "Created: viewForm <-- " << qPrintable(parent->objectName()); //for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget()) // std::cout << " <-- " << qPrintable(parent->objectName()); //std::cout << std::endl; //parent = viewForm; //std::cout << "Created control: QCTabBar <-- " << qPrintable(parent->objectName()); //for (parent = parent->parentWidget(); parent != 0; parent = parent->parentWidget()) // std::cout << " <-- " << qPrintable(parent->objectName()); //std::cout << std::endl; //attachListeners(control, false); // viewForm = new ViewForm(control, SWT.FLAT); // attachListeners(viewForm, false); // systemToolbar = new StandardSystemToolbar(viewForm, true, false, true, true, true); // systemToolbar.addListener(systemToolbarListener); // viewForm.setTopRight(systemToolbar.getControl()); // // topCenter = new ProxyControl(viewForm); // topCenterCache = new SizeCache(); // // title = new CLabel(viewForm, SWT.LEFT); // attachListeners(title, false); // viewForm.setTopLeft(title); ctkServiceReference serviceRef = WorkbenchPlugin::GetDefault()->GetPluginContext()->getServiceReference(); if (serviceRef) { skinManager = WorkbenchPlugin::GetDefault()->GetPluginContext()->getService(serviceRef); } } NativeTabFolder::~NativeTabFolder() { if (!PlatformUI::GetWorkbench()->IsClosing()) { BERRY_DEBUG << "Deleting viewForm"; if (content != 0) { content->setParent(0); } viewForm->deleteLater(); } } bool NativeTabFolder::eventFilter(QObject* watched, QEvent* event) { if (event->type() == QEvent::MouseButtonPress) { QMouseEvent* mouseEvent = static_cast(event); this->HandleMousePress(mouseEvent->pos()); } return QObject::eventFilter(watched, event); } void NativeTabFolder::UpdateColors() { QString tabStyle = this->GetActive() == 1 ? skinManager->GetActiveTabStylesheet() : skinManager->GetTabStylesheet(); //tabControl->setStyleSheet(tabSkin); //contentFrame->setStyleSheet(tabSkin); viewForm->setStyleSheet(tabStyle); } void NativeTabFolder::SetActive(int activeState) { AbstractTabFolder::SetActive(activeState); this->UpdateColors(); } void NativeTabFolder::CloseButtonClicked(AbstractTabItem* item) { this->FireEvent(TabFolderEvent::EVENT_CLOSE, item); } QSize NativeTabFolder::ComputeSize(int /*widthHint*/, int /*heightHint*/) { return QSize(50,50); } AbstractTabItem* NativeTabFolder::Add(int index, int flags) { NativeTabItem* item = new NativeTabItem(this, index, flags); return item; } void NativeTabFolder::Move(int from, int to) { int tabCount = tabControl->count(); if (to > tabCount) to = tabCount; tabControl->moveAbstractTab(from, to); } void NativeTabFolder::Layout(bool flushCache) { AbstractTabFolder::Layout(flushCache); // QRect rect1 = tabControl->geometry(); // QRect rect2 = viewForm->geometry(); // std::cout << "QCTabBar geometry is: x=" << rect1.x() << ", y=" << rect1.y() << ", width=" << rect1.width() << ", height=" << rect1.height() << std::endl; // std::cout << "ViewForm geometry is: " << rect2.x() << ", y=" << rect2.y() << ", width=" << rect2.width() << ", height=" << rect2.height() << std::endl; // Rectangle oldBounds = viewForm.getBounds(); // Rectangle newBounds = control.getClientArea(); // // viewForm.setBounds(newBounds); // // if (Util.equals(oldBounds, newBounds)) // { // viewForm.layout(flushCache); // } } QPoint NativeTabFolder::GetPaneMenuLocation() { return AbstractTabFolder::GetPaneMenuLocation(); //return systemToolbar.getPaneMenuLocation(); } void NativeTabFolder::SetState(int state) { AbstractTabFolder::SetState(state); //systemToolbar.setState(state); } QRect NativeTabFolder::GetClientArea() { if (content == 0) { return QRect(); } return content->geometry(); } QList NativeTabFolder::GetItems() { return tabControl->getTabs(); } void NativeTabFolder::SetSelection(AbstractTabItem* toSelect) { if (toSelect == 0) { return; } tabControl->setCurrentTab(toSelect); } void NativeTabFolder::SetSelectedInfo(const PartInfo& /*info*/) { // if (!Util.equals(title.getText(), info.title)) // { // title.setText(info.title); // } // if (title.getImage() != info.image) // { // title.setImage(info.image); // } } QRect NativeTabFolder::GetTabArea() { return tabControl->geometry(); // Rectangle bounds = control.getBounds(); // // Rectangle clientArea = control.getClientArea(); // // bounds.x = 0; // bounds.y = 0; // Geometry.expand(bounds, 0, 0, -(clientArea.height + clientArea.y), 0); // // return Geometry.toDisplay(control.getParent(), bounds); } QWidget* NativeTabFolder::GetControl() { return viewForm; } bool NativeTabFolder::IsOnBorder(const QPoint& /*globalPos*/) { // Point localPos = getControl().toControl(globalPos); // // Rectangle clientArea = getClientArea(); // return localPos.y > clientArea.y && localPos.y < clientArea.y // + clientArea.height; return false; } AbstractTabItem* NativeTabFolder::GetSelection() { return tabControl->getCurrentTab(); } QWidget* NativeTabFolder::GetContentParent() { return contentFrame; } void NativeTabFolder::SetContent(QWidget* newContent) { //viewForm.setContent(newContent); if (content != 0) { contentFrame->layout()->removeWidget(content); disconnect(content); } content = newContent; content->installEventFilter(this); //((QBoxLayout*)contentFrame->layout())->addWidget(content, 1); contentFrame->layout()->addWidget(content); } QCTabBar* NativeTabFolder::GetTabFolder() { return tabControl; } void NativeTabFolder::SetSelectedTitle(const QString& /*newTitle*/) { //title.setText(newTitle); } void NativeTabFolder::SetSelectedImage(const QPixmap* /*image*/) { //title.setImage(image); } AbstractTabItem* NativeTabFolder::GetItem(const QPoint& toFind) { QPoint localPoint = tabControl->mapFromGlobal(toFind); int index = tabControl->tabAt(localPoint); if (index < 0) return 0; return tabControl->getTab(index); } void NativeTabFolder::EnablePaneMenu(bool /*enabled*/) { //systemToolbar.enablePaneMenu(enabled); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp index e610a3c2d3..866b606fa2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp @@ -1,436 +1,436 @@ /*=================================================================== 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 "internal/berryQtWidgetsTweaklet.h" #include "berryPresentablePartFolder.h" #include "berryAbstractTabItem.h" #include #include #include namespace berry { PresentablePartFolder::ContentProxyListener::ContentProxyListener( PresentablePartFolder* folder) : folder(folder) { } GuiTk::IControlListener::Events::Types PresentablePartFolder::ContentProxyListener::GetEventTypes() const { return static_cast(Events::MOVED & Events::RESIZED); } void PresentablePartFolder::ContentProxyListener::ControlMoved( GuiTk::ControlEvent::Pointer /*e*/) { folder->LayoutContent(); } void PresentablePartFolder::ContentProxyListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { } PresentablePartFolder::ShellListener::ShellListener(AbstractTabFolder* _folder) : folder(_folder) { } void PresentablePartFolder::ShellListener::ShellActivated(const ShellEvent::Pointer& /*e*/) { folder->ShellActive(true); } void PresentablePartFolder::ShellListener::ShellDeactivated( const ShellEvent::Pointer& /*e*/) { folder->ShellActive(false); } PresentablePartFolder::ChildPropertyChangeListener::ChildPropertyChangeListener( PresentablePartFolder* folder) : presentablePartFolder(folder) { } void PresentablePartFolder::ChildPropertyChangeListener::PropertyChange( const Object::Pointer& source, int property) { if (source.Cast () != 0) { IPresentablePart::Pointer part = source.Cast (); presentablePartFolder->ChildPropertyChanged(part, property); } } PartInfo PresentablePartFolder::tempPartInfo = PartInfo(); void PresentablePartFolder::LayoutContent() { if (current != 0) { - Rectangle clientArea = DragUtil::GetDisplayBounds(contentProxy); + QRect clientArea = DragUtil::GetDisplayBounds(contentProxy); - Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl( + QRect bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl( folder->GetControl()->parentWidget(), clientArea); current->SetBounds(bounds); } } void PresentablePartFolder::InternalRemove(IPresentablePart::Pointer toRemove) { AbstractTabItem* item = this->GetTab(toRemove); if (item != 0) { item->Dispose(); } // do not use item anymore! if (std::find(partList.begin(), partList.end(), toRemove) != partList.end()) { toRemove->RemovePropertyListener(childPropertyChangeListener.data()); partList.removeAll(toRemove); } } void PresentablePartFolder::ChildPropertyChanged( IPresentablePart::Pointer part, int property) { AbstractTabItem* tab = this->GetTab(part); if (property == IPresentablePart::PROP_HIGHLIGHT_IF_BACK) { if (tab != 0 && this->GetCurrent() != part) {//Set bold if it doesn't currently have focus tab->SetBold(true); this->InitTab(tab, part); } } // else if (property == IPresentablePart::PROP_TOOLBAR) // { // if (tab != 0 && this->GetCurrent() == part) // { // folder->FlushToolbarSize(); // } // if (tab != 0) // { // this->InitTab(tab, part); // if (this->GetCurrent() == part) // { // this->Layout(true); // } // } else if (property == IPresentablePart::PROP_CONTENT_DESCRIPTION || property == IPresentablePart::PROP_PANE_MENU || property == IPresentablePart::PROP_TITLE) { if (tab != 0) { this->InitTab(tab, part); if (this->GetCurrent() == part) { this->Layout(true); } } } else if (property == IPresentablePart::PROP_PREFERRED_SIZE) { TabFolderEvent::Pointer event( new TabFolderEvent(TabFolderEvent::EVENT_PREFERRED_SIZE, tab, 0, 0)); folder->FireEvent(event); } else { if (tab != 0) this->InitTab(tab, part); } } PresentablePartFolder::~PresentablePartFolder() { Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetShell(folder->GetControl())->RemoveShellListener( shellListener.data()); for (QList::iterator iter = partList.begin(); iter != partList.end(); ++iter) { (*iter)->RemovePropertyListener(childPropertyChangeListener.data()); } for (QWidget* currentWidget = contentProxy; currentWidget != 0 && currentWidget != folder->GetControl()->parentWidget(); currentWidget = currentWidget->parentWidget()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(currentWidget, contentListener); } BERRY_DEBUG << "DELETING PresentablePartFolder and contentProxy\n"; delete folder; } void PresentablePartFolder::InitTab(AbstractTabItem* item, IPresentablePart::Pointer part) { tempPartInfo.Set(part); item->SetInfo(tempPartInfo); item->SetBusy(part->IsBusy()); if (part == this->GetCurrent()) { folder->SetSelectedInfo(tempPartInfo); //TODO Pane menu //folder->EnablePaneMenu(part->GetMenu() != 0); //setToolbar(part.getToolBar()); } } PresentablePartFolder::PresentablePartFolder(AbstractTabFolder* _folder) : folder(_folder), isVisible(true), shellListener(new ShellListener(folder)), childPropertyChangeListener(new ChildPropertyChangeListener(this)) { Shell::Pointer controlShell = Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetShell(folder->GetControl()); controlShell->AddShellListener(shellListener.data()); folder->ShellActive(Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetActiveShell() == controlShell); //folder.getControl().addDisposeListener(tabDisposeListener); //toolbarProxy = new ProxyControl(folder.getToolbarParent()); // NOTE: if the shape of contentProxy changes, the fix for bug 85899 in EmptyTabFolder.computeSize may need adjustment. contentListener = new ContentProxyListener(this); contentProxy = new QtControlWidget(folder->GetContentParent(), 0); contentProxy->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //contentProxy->setVisible(false); for (QWidget* currentWidget = contentProxy; currentWidget != 0 && currentWidget != folder->GetControl()->parentWidget(); currentWidget = currentWidget->parentWidget()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(currentWidget, contentListener); } folder->SetContent(contentProxy); } QList PresentablePartFolder::GetPartList() { QList items = folder->GetItems(); QList result; for (int i = 0; i < items.size(); i++) { result.push_back(this->GetPartForTab(items[i])); } return result; } void PresentablePartFolder::Insert(IPresentablePart::Pointer part, int idx) { poco_assert(folder->GetControl() != 0); if (this->GetTab(part) != 0) { if (this->IndexOf(part) != idx) this->Move(part, idx); return; } idx = std::min(idx, static_cast(folder->GetItemCount())); AbstractTabItem* item = 0; int style = 0; if (part->IsCloseable()) { style |= Constants::CLOSE; } item = folder->Add(idx, style); item->SetData(part); this->InitTab(item, part); part->AddPropertyListener(childPropertyChangeListener.data()); partList.push_back(part); } void PresentablePartFolder::Remove(IPresentablePart::Pointer toRemove) { if (toRemove == current) { this->Select(IPresentablePart::Pointer(0)); } this->InternalRemove(toRemove); } void PresentablePartFolder::Move(IPresentablePart::Pointer part, int newIndex) { int currentIndex = this->IndexOf(part); if (currentIndex == newIndex) { return; } folder->Move(currentIndex, newIndex); //this->InternalRemove(part); //this->Insert(part, newIndex); //if (current == part) //{ // folder->SetSelection(this->GetTab(part)); //} } int PresentablePartFolder::Size() { return folder->GetItemCount(); } void PresentablePartFolder::SetBounds(const QRect& bounds) { QSize minSize = folder->ComputeSize(bounds.width(), Constants::DEFAULT); QRect newBounds(bounds); if (folder->GetState() == IStackPresentationSite::STATE_MINIMIZED && minSize.height() < bounds.height()) { newBounds.setHeight(minSize.height()); } // Set the tab folder's bounds folder->GetControl()->setGeometry(newBounds); this->Layout(false); } void PresentablePartFolder::Select(IPresentablePart::Pointer toSelect) { if (toSelect == current) { return; } if (toSelect != 0) { toSelect->SetVisible(true); } if (current != 0) { current->SetVisible(false); //setToolbar(null); } current = toSelect; AbstractTabItem* selectedItem = this->GetTab(toSelect); folder->SetSelection(selectedItem); if (selectedItem != 0) { // Determine if we need to un-bold this tab selectedItem->SetBold(false); this->InitTab(selectedItem, toSelect); } // else // { // setToolbar(null); // } this->Layout(true); } IPresentablePart::Pointer PresentablePartFolder::GetPartForTab( AbstractTabItem* tab) { if (tab == 0) { return IPresentablePart::Pointer(0); } IPresentablePart::Pointer part = tab->GetData().Cast (); return part; } AbstractTabItem* PresentablePartFolder::GetTab(IPresentablePart::Pointer part) { return folder->FindItem(part); } int PresentablePartFolder::IndexOf(IPresentablePart::Pointer part) { AbstractTabItem* item = this->GetTab(part); if (item == 0) { return -1; } return folder->IndexOf(item); } AbstractTabFolder* PresentablePartFolder::GetTabFolder() { return folder; } void PresentablePartFolder::SetVisible(bool isVisible) { this->isVisible = isVisible; this->GetTabFolder()->SetVisible(isVisible); if (isVisible) { this->Layout(true); } } void PresentablePartFolder::Layout(bool changed) { if (!isVisible) { // Don't bother with layout if we're not visible return; } // Lay out the tab folder and compute the client area folder->Layout(changed); //toolbarProxy.layout(); this->LayoutContent(); } IPresentablePart::Pointer PresentablePartFolder::GetCurrent() { return current; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.cpp index f7e7ad2a71..250f447770 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.cpp @@ -1,139 +1,137 @@ /*=================================================================== 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 "berryReplaceDragHandler.h" #include "berryAbstractTabItem.h" #include #include namespace berry { ReplaceDragHandler::DragCookie::DragCookie(int pos) : insertPosition(pos) { } ReplaceDragHandler::ReplaceDragHandler(AbstractTabFolder* folder) : tabFolder(folder) { } StackDropResult::Pointer ReplaceDragHandler::DragOver(QWidget*, - const Point& location, int dragStart) + const QPoint& location, int dragStart) { // Determine which tab we're currently dragging over //Point localPos = tabFolder.getControl().toControl(location); - QPoint point(location.x, location.y); - AbstractTabItem* tabUnderPointer = tabFolder->GetItem(point); + AbstractTabItem* tabUnderPointer = tabFolder->GetItem(location); // This drop target only deals with tabs... if we're not dragging over // a tab, exit. if (tabUnderPointer == 0) { QRect titleArea = tabFolder->GetTabArea(); // If we're dragging over the title area, treat this as a drop in the last // tab position. - if (titleArea.contains(point) && tabFolder->GetItemCount() > 0) + if (titleArea.contains(location) && tabFolder->GetItemCount() > 0) { int dragOverIndex = static_cast(tabFolder->GetItemCount()); AbstractTabItem* lastTab = tabFolder->GetItem(dragOverIndex - 1); // Can't drag to end unless you can see the end if (!lastTab->IsShowing()) { return StackDropResult::Pointer(0); } // If we are unable to compute the bounds for this tab, then ignore the drop - QRect qlastTabBounds = lastTab->GetBounds(); - Rectangle lastTabBounds(qlastTabBounds.x(), qlastTabBounds.y(), qlastTabBounds.width(), qlastTabBounds.height()); - if (qlastTabBounds.isEmpty()) + QRect lastTabBounds = lastTab->GetBounds(); + if (lastTabBounds.isEmpty()) { return StackDropResult::Pointer(0); } if (dragStart >= 0) { dragOverIndex--; Object::Pointer cookie(new DragCookie(dragOverIndex)); StackDropResult::Pointer result(new StackDropResult(lastTabBounds, cookie)); return result; } // Make the drag-over rectangle look like a tab at the end of the tab region. // We don't actually know how wide the tab will be when it's dropped, so just // make it 3 times wider than it is tall. - Rectangle dropRectangle(titleArea.x(), titleArea.y(), titleArea.width(), titleArea.height()); + QRect dropRectangle = titleArea; - dropRectangle.x = lastTabBounds.x + lastTabBounds.width; - dropRectangle.width = 3 * dropRectangle.height; + dropRectangle.setX(lastTabBounds.x() + lastTabBounds.width()); + dropRectangle.setWidth(3 * dropRectangle.height()); Object::Pointer cookie(new DragCookie(dragOverIndex)); StackDropResult::Pointer result(new StackDropResult(dropRectangle, cookie)); return result; } else { // If the closest side is the side with the tabs, consider this a stack operation. // Otherwise, let the drop fall through to whatever the default behavior is - Rectangle displayBounds = DragUtil::GetDisplayBounds( + QRect displayBounds = DragUtil::GetDisplayBounds( tabFolder->GetControl()); int closestSide = Geometry::GetClosestSide(displayBounds, location); if (closestSide == tabFolder->GetTabPosition()) { StackDropResult::Pointer result(new StackDropResult(displayBounds, Object::Pointer(0))); return result; } return StackDropResult::Pointer(0); } } if (!tabUnderPointer->IsShowing()) { return StackDropResult::Pointer(0); } QRect qtabBounds = tabUnderPointer->GetBounds(); - Rectangle tabBounds(qtabBounds.x(), qtabBounds.y(), qtabBounds.width(), qtabBounds.height()); + QRect tabBounds(qtabBounds.x(), qtabBounds.y(), qtabBounds.width(), qtabBounds.height()); if (qtabBounds.isEmpty()) { return StackDropResult::Pointer(0); } Object::Pointer cookie(new DragCookie(tabFolder->IndexOf(tabUnderPointer))); StackDropResult::Pointer result(new StackDropResult(tabBounds, cookie)); return result; } int ReplaceDragHandler::GetInsertionPosition(Object::Pointer cookie) { if (cookie.Cast() != 0) { return std::min(static_cast(tabFolder->GetItemCount()), cookie.Cast()->insertPosition); } return static_cast(tabFolder->GetItemCount()); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.h index 7202f0d6ae..4587fac478 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryReplaceDragHandler.h @@ -1,58 +1,58 @@ /*=================================================================== 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 BERRYREPLACEDRAGHANDLER_H_ #define BERRYREPLACEDRAGHANDLER_H_ #include "berryTabDragHandler.h" #include "berryAbstractTabFolder.h" namespace berry { class ReplaceDragHandler : public TabDragHandler { private: struct DragCookie : public Object { int insertPosition; DragCookie(int pos); }; AbstractTabFolder* tabFolder; public: ReplaceDragHandler(AbstractTabFolder* folder); /* (non-Javadoc) * @see org.eclipse.ui.internal.presentations.util.TabDragHandler#dragOver(org.eclipse.swt.widgets.Control, org.eclipse.swt.graphics.Point) */ - StackDropResult::Pointer DragOver(QWidget*, const Point& location, + StackDropResult::Pointer DragOver(QWidget*, const QPoint& location, int dragStart); /* (non-Javadoc) * @see org.eclipse.ui.internal.presentations.util.TabDragHandler#getInsertionPosition(java.lang.Object) */ int GetInsertionPosition(Object::Pointer cookie); }; } #endif /* BERRYREPLACEDRAGHANDLER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabDragHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabDragHandler.h index 9a231b5a12..e1caa5786a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabDragHandler.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabDragHandler.h @@ -1,51 +1,51 @@ /*=================================================================== 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 BERRYTABDRAGHANDLER_H_ #define BERRYTABDRAGHANDLER_H_ #include #include #include #include namespace berry { struct BERRY_UI_QT TabDragHandler { virtual ~TabDragHandler(); /** * Returns the StackDropResult for the location being dragged over. * * @param currentControl control being dragged over * @param location mouse position (display coordinates) * @param initialTab the index of the tab in this stack being dragged, * or -1 if dragging a tab from another stack. * @return the StackDropResult for this drag location */ virtual StackDropResult::Pointer DragOver(QWidget* currentControl, - const Point& location, int initialTab) = 0; + const QPoint& location, int initialTab) = 0; virtual int GetInsertionPosition(Object::Pointer cookie) = 0; }; } #endif /* BERRYTABDRAGHANDLER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp index a614847301..b0ec449337 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp @@ -1,501 +1,499 @@ /*=================================================================== 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 "berryIMemento.h" #include "berryTabbedStackPresentation.h" #include "berryAbstractTabItem.h" #include "berryLeftToRightTabOrder.h" #include "berryReplaceDragHandler.h" #include "berryShell.h" #include namespace berry { int TabbedStackPresentation::ComputePreferredMinimumSize(bool width, int availablePerpendicular) { int minSize; int hint = availablePerpendicular == INF ? Constants::DEFAULT : availablePerpendicular; if (width) { minSize = folder->GetTabFolder()->ComputeSize(Constants::DEFAULT, hint).width(); } else { minSize = folder->GetTabFolder()->ComputeSize(hint, Constants::DEFAULT).height(); } return minSize; } void TabbedStackPresentation::HandleTabFolderEvent(TabFolderEvent::Pointer e) { int type = e->type; if (type == TabFolderEvent::EVENT_MINIMIZE) { this->GetSite()->SetState(IStackPresentationSite::STATE_MINIMIZED); } else if (type == TabFolderEvent::EVENT_MAXIMIZE) { this->GetSite()->SetState(IStackPresentationSite::STATE_MAXIMIZED); } else if (type == TabFolderEvent::EVENT_RESTORE) { this->GetSite()->SetState(IStackPresentationSite::STATE_RESTORED); } else if (type == TabFolderEvent::EVENT_CLOSE) { IPresentablePart::Pointer part = folder->GetPartForTab(e->tab); if (part != 0) { QList parts; parts.push_back(part); this->GetSite()->Close(parts); } } else if (type == TabFolderEvent::EVENT_SHOW_LIST) { this->ShowPartList(); } else if (type == TabFolderEvent::EVENT_GIVE_FOCUS_TO_PART) { IPresentablePart::Pointer part = this->GetSite()->GetSelectedPart(); if (part != 0) { part->SetFocus(); } } else if (type == TabFolderEvent::EVENT_PANE_MENU) { IPresentablePart::Pointer part = this->GetSite()->GetSelectedPart(); if (part != 0) { part->SetFocus(); } //this->ShowPaneMenu(folder->GetPartForTab(e->tab), QPoint(e->x, e->y)); } else if (type == TabFolderEvent::EVENT_DRAG_START) { AbstractTabItem* beingDragged = e->tab; - Point initialLocation(e->x, e->y); + QPoint initialLocation(e->x, e->y); if (beingDragged == 0) { this->GetSite()->DragStart(initialLocation, false); } else { IPresentablePart::Pointer part = folder->GetPartForTab(beingDragged); try { dragStart = folder->IndexOf(part); // hold on to this TabbedStackPresentation instance, because // in this->GetSite()->DragStart() all reference may be deleted // and this instance is destroyed, leading to a seg fault when // trying to write to dragStart StackPresentation::Pointer tabbedStackPresentation(this); this->GetSite()->DragStart(part, initialLocation, false); dragStart = -1; } catch(const std::exception& exc) { dragStart = -1; throw exc; } } } else if (type == TabFolderEvent::EVENT_TAB_SELECTED) { if (ignoreSelectionChanges > 0) { return; } IPresentablePart::Pointer part = folder->GetPartForTab(e->tab); if (part != 0) { this->GetSite()->SelectPart(part); } } else if (type == TabFolderEvent::EVENT_SYSTEM_MENU) { IPresentablePart::Pointer part = folder->GetPartForTab(e->tab); if (part == 0) { part = this->GetSite()->GetSelectedPart(); } if (part != 0) { //this->ShowSystemMenu(QPoint(e->x, e->y), part); } } else if (type == TabFolderEvent::EVENT_PREFERRED_SIZE) { IPresentablePart::Pointer part = folder->GetPartForTab(e->tab); if (part == 0) { // Standalone views with no title have no tab, so just get the part. QList parts = this->GetSite()->GetPartList(); if (parts.size() > 0) part = parts.front(); } if (part == this->GetSite()->GetSelectedPart()) { this->GetSite()->FlushLayout(); } } } TabbedStackPresentation::TabbedStackPresentation( IStackPresentationSite::Pointer site, AbstractTabFolder* widget/*, ISystemMenu systemMenu*/) : StackPresentation(site) { PresentablePartFolder* folder = new PresentablePartFolder(widget); this->Init(site, folder, new LeftToRightTabOrder(folder), new ReplaceDragHandler(widget)); // systemMenu); } TabbedStackPresentation::TabbedStackPresentation( IStackPresentationSite::Pointer site, PresentablePartFolder* folder/*, ISystemMenu systemMenu*/) : StackPresentation(site) { this->Init(site, folder, new LeftToRightTabOrder(folder), new ReplaceDragHandler(folder->GetTabFolder())); //, systemMenu); } TabbedStackPresentation::TabbedStackPresentation( IStackPresentationSite::Pointer site, PresentablePartFolder* newFolder, TabOrder* tabs, TabDragHandler* dragBehavior /*, ISystemMenu systemMenu*/) : StackPresentation(site) { this->Init(site, newFolder, tabs, dragBehavior); } void TabbedStackPresentation::Init(IStackPresentationSite::Pointer, PresentablePartFolder* newFolder, TabOrder* tabs, TabDragHandler* dragBehavior /*, ISystemMenu systemMenu*/) { //this->systemMenu = systemMenu; initializing = true; ignoreSelectionChanges = 0; dragStart = -1; this->folder = newFolder; this->tabs = tabs; this->dragBehavior = dragBehavior; // // Add a dispose listener. This will call the presentationDisposed() // // method when the widget is destroyed. // folder.getTabFolder().getControl().addDisposeListener(new DisposeListener() { // public void widgetDisposed(DisposeEvent e) { // presentationDisposed(); // } // }); folder->GetTabFolder()->tabFolderEvent += TabFolderEventDelegate(this, &TabbedStackPresentation::HandleTabFolderEvent); //this->partList = new DefaultPartList(site, newFolder); } void TabbedStackPresentation::RestoreState(IPresentationSerializer* serializer, IMemento::Pointer savedState) { tabs->RestoreState(serializer, savedState); } void TabbedStackPresentation::SaveState(IPresentationSerializer* context, IMemento::Pointer memento) { StackPresentation::SaveState(context, memento); tabs->SaveState(context, memento); } -void TabbedStackPresentation::SetBounds(const Rectangle& bounds) +void TabbedStackPresentation::SetBounds(const QRect& bounds) { - QRect rectangle(bounds.x, bounds.y, bounds.width, bounds.height); - folder->SetBounds(rectangle); + folder->SetBounds(bounds); } -Point TabbedStackPresentation::ComputeMinimumSize() +QSize TabbedStackPresentation::ComputeMinimumSize() { - QSize point = folder->GetTabFolder()->ComputeSize(Constants::DEFAULT, Constants::DEFAULT); - return Point(point.width(), point.height()); + return folder->GetTabFolder()->ComputeSize(Constants::DEFAULT, Constants::DEFAULT); } int TabbedStackPresentation::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult) { // If there is exactly one part in the stack, this just returns the // preferred size of the part as the preferred size of the stack. QList parts = this->GetSite()->GetPartList(); if (parts.size() == 1 && parts.front() != 0 && !(this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED)) { int partSize = parts.front()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredResult); if (partSize == INF) return partSize; // Adjust preferred size to take into account tab and border trim. int minSize = this->ComputePreferredMinimumSize(width, availablePerpendicular); if (width) { // PaneFolder adds some bogus tab spacing, so just find the maximum width. partSize = std::max(minSize, partSize); } else { // Add them (but only if there's enough room) if (INF - minSize > partSize) partSize += minSize; } return partSize; } if (preferredResult != INF || this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED) { int minSize = this->ComputePreferredMinimumSize(width, availablePerpendicular); if (this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED) { return minSize; } return std::max(minSize, preferredResult); } return INF; } int TabbedStackPresentation::GetSizeFlags(bool width) { int flags = 0; // If there is exactly one part in the stack, // then take into account the size flags of the part. QList parts = this->GetSite()->GetPartList(); if (parts.size() == 1 && parts.front() != 0) { flags |= parts.front()->GetSizeFlags(width); } return flags | StackPresentation::GetSizeFlags(width); } void TabbedStackPresentation::ShowPartList() { // if (partList != 0) // { // int numberOfParts = folder->GetTabFolder()->GetItemCount(); // if (numberOfParts > 0) // { // partList.show(getControl(), folder.getTabFolder() .getPartListLocation(), // getSite().getSelectedPart()); // } // } } TabbedStackPresentation::~TabbedStackPresentation() { // // Dispose the tab folder's widgetry // folder.getTabFolder().getControl().dispose(); BERRY_DEBUG << "DELETING TabbedStackPresentation\n"; delete tabs; delete dragBehavior; delete folder; } void TabbedStackPresentation::SetActive(int newState) { folder->GetTabFolder()->SetActive(newState); } void TabbedStackPresentation::SetVisible(bool isVisible) { IPresentablePart::Pointer current = this->GetSite()->GetSelectedPart(); if (current != 0) { current->SetVisible(isVisible); } folder->SetVisible(isVisible); } void TabbedStackPresentation::SetState(int state) { folder->GetTabFolder()->SetState(state); } void* TabbedStackPresentation::GetControl() { return folder->GetTabFolder()->GetControl(); } AbstractTabFolder* TabbedStackPresentation::GetTabFolder() { return folder->GetTabFolder(); } void TabbedStackPresentation::AddPart(IPresentablePart::Pointer newPart, Object::Pointer cookie) { ++ignoreSelectionChanges; try { if (initializing) { tabs->AddInitial(newPart); } else { if (cookie == 0) { tabs->Add(newPart); } else { int insertionPoint = dragBehavior->GetInsertionPosition(cookie); tabs->Insert(newPart, insertionPoint); } } --ignoreSelectionChanges; } catch (std::exception& e) { --ignoreSelectionChanges; throw e; } if (tabs->GetPartList().size() == 1) { if (newPart->GetSizeFlags(true) != 0 || newPart->GetSizeFlags(false) != 0) { this->GetSite()->FlushLayout(); } } } void TabbedStackPresentation::MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie) { ++ignoreSelectionChanges; try { int insertionPoint = dragBehavior->GetInsertionPosition(cookie); if (insertionPoint == folder->IndexOf(toMove)) { --ignoreSelectionChanges; return; } tabs->Move(toMove, insertionPoint); --ignoreSelectionChanges; } catch (std::exception& e) { --ignoreSelectionChanges; throw e; } } void TabbedStackPresentation::RemovePart(IPresentablePart::Pointer oldPart) { ++ignoreSelectionChanges; try { tabs->Remove(oldPart); --ignoreSelectionChanges; } catch (std::exception& e) { --ignoreSelectionChanges; throw e; } } void TabbedStackPresentation::SelectPart(IPresentablePart::Pointer toSelect) { initializing = false; tabs->Select(toSelect); } -StackDropResult::Pointer TabbedStackPresentation::DragOver(void* currentControl, const Point& location) +StackDropResult::Pointer TabbedStackPresentation::DragOver(void* currentControl, const QPoint& location) { QWidget* currentWidget = static_cast(currentControl); return dragBehavior->DragOver(currentWidget, location, dragStart); } QList TabbedStackPresentation::GetTabList( IPresentablePart::Pointer part) { QList list; if (folder->GetTabFolder()->GetTabPosition() == Constants::BOTTOM) { if (part->GetControl() != 0) { list.push_back(part->GetControl()); } } list.push_back(folder->GetTabFolder()->GetControl()); // if (part->GetToolBar() != 0) // { // list.push_back(part->GetToolBar()); // } if (folder->GetTabFolder()->GetTabPosition() == Constants::TOP) { if (part->GetControl() != 0) { list.push_back(part->GetControl()); } } return list; } void TabbedStackPresentation::MoveTab(IPresentablePart::Pointer part, int index) { tabs->Move(part, index); folder->Layout(true); } QList TabbedStackPresentation::GetPartList() { return tabs->GetPartList(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.h index f77772f225..359ff6f791 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.h @@ -1,276 +1,276 @@ /*=================================================================== 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 BERRYTABBEDSTACKPRESENTATION_H_ #define BERRYTABBEDSTACKPRESENTATION_H_ #include #include "berryPresentablePartFolder.h" #include "berryTabOrder.h" #include "berryTabDragHandler.h" namespace berry { class TabbedStackPresentation : public StackPresentation { private: typedef MessageDelegate1 TabFolderEventDelegate; PresentablePartFolder* folder; //ISystemMenu systemMenu; //ISystemMenu partList; // PreferenceStoreAdapter apiPreferences = new PreferenceStoreAdapter(PrefUtil // .getAPIPreferenceStore()); // ThemeManagerAdapter themePreferences = new ThemeManagerAdapter( // PlatformUI.getWorkbench().getThemeManager()); TabOrder* tabs; TabDragHandler* dragBehavior; bool initializing; int ignoreSelectionChanges; int dragStart; //Map prefs = new HashMap(); /** * Returns the minimum size for this stack, taking into account * the available perpendicular space. * @param width indicates whether a width (=true) or a height (=false) is being computed * @param availablePerpendicular available space perpendicular to the direction being measured * or INFINITE if unbounded (pixels). * @return returns the preferred minimum size (pixels). * This is a width if width == true or a height if width == false. */ int ComputePreferredMinimumSize(bool width, int availablePerpendicular); public: void HandleTabFolderEvent(TabFolderEvent::Pointer e); /** * Creates a TabbedStackPresentation. The created object will take ownership of the AbstractTabFolder pointer. */ TabbedStackPresentation(IStackPresentationSite::Pointer site, AbstractTabFolder* widget/*, ISystemMenu systemMenu*/); /** * Creates a TabbedStackPresentation. The created object will take ownership of the PresentablePartFolder pointer. */ TabbedStackPresentation(IStackPresentationSite::Pointer site, PresentablePartFolder* folder/*, ISystemMenu systemMenu*/); /** * Creates a TabbedStackPresentation. The created object will take ownership of the PresentablePartFolder and the TabOrder pointer. */ TabbedStackPresentation(IStackPresentationSite::Pointer site, PresentablePartFolder* newFolder, TabOrder* tabs, TabDragHandler* dragBehavior /*, ISystemMenu systemMenu*/); void Init(IStackPresentationSite::Pointer, PresentablePartFolder* newFolder, TabOrder* tabs, TabDragHandler* dragBehavior /*, ISystemMenu systemMenu*/); /** * Restores a presentation from a previously stored state * * @param serializer (not null) * @param savedState (not null) */ void RestoreState(IPresentationSerializer* serializer, IMemento::Pointer savedState); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#saveState(org.blueberry.ui.presentations.IPresentationSerializer, org.blueberry.ui.IMemento) */ void SaveState(IPresentationSerializer* context, IMemento::Pointer memento); /* (non-Javadoc) - * @see org.blueberry.ui.presentations.StackPresentation#setBounds(org.blueberry.swt.graphics.Rectangle) + * @see org.blueberry.ui.presentations.StackPresentation#setBounds(org.blueberry.swt.graphics.QRect) */ - void SetBounds(const Rectangle& bounds); + void SetBounds(const QRect& bounds); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#computeMinimumSize() */ - Point ComputeMinimumSize(); + QSize ComputeMinimumSize(); /* (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.presentations.StackPresentation#getSizeFlags(boolean) */ int GetSizeFlags(bool width); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#showPartList() */ void ShowPartList(); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#dispose() */ ~TabbedStackPresentation(); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#setActive(int) */ void SetActive(int newState); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#setVisible(boolean) */ void SetVisible(bool isVisible); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#setState(int) */ void SetState(int state); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#getControl() */ void* GetControl(); /** * @return AbstractTabFolder the presentation's tab folder */ AbstractTabFolder* GetTabFolder(); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#addPart(org.blueberry.ui.presentations.IPresentablePart, java.lang.Object) */ void AddPart(IPresentablePart::Pointer newPart, Object::Pointer cookie); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#movePart(org.blueberry.ui.presentations.IPresentablePart, java.lang.Object) */ void MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#removePart(org.blueberry.ui.presentations.IPresentablePart) */ void RemovePart(IPresentablePart::Pointer oldPart); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#selectPart(org.blueberry.ui.presentations.IPresentablePart) */ void SelectPart(IPresentablePart::Pointer toSelect); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#DragOver(void*, const Point&) */ - StackDropResult::Pointer DragOver(void* currentControl, const Point& location); + StackDropResult::Pointer DragOver(void* currentControl, const QPoint& location); // void showSystemMenu() { // showSystemMenu(folder.getTabFolder().getSystemMenuLocation(), getSite().getSelectedPart()); // } // void showSystemMenu(Point displayCoordinates, IPresentablePart context) { // if (context != getSite().getSelectedPart()) { // getSite().selectPart(context); // } // systemMenu.show(getControl(), displayCoordinates, context); // } // /* (non-Javadoc) // * @see org.blueberry.ui.presentations.StackPresentation#showPaneMenu() // */ // void showPaneMenu() { // IPresentablePart part = getSite().getSelectedPart(); // // if (part != null) { // showPaneMenu(part, folder.getTabFolder().getPaneMenuLocation()); // } // } // void showPaneMenu(IPresentablePart part, Point location) { // Assert.isTrue(!isDisposed()); // // IPartMenu menu = part.getMenu(); // // if (menu != null) { // menu.showMenu(location); // } // } /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#getTabList(org.blueberry.ui.presentations.IPresentablePart) */ QList GetTabList(IPresentablePart::Pointer part); // void SetPartList(ISystemMenu menu) { // this.partList = menu; // } // IDynamicPropertyMap getTheme() { // return themePreferences; // } // IDynamicPropertyMap getApiPreferences() { // return apiPreferences; // } // IDynamicPropertyMap getPluginPreferences(Plugin toQuery) { // String id = toQuery.getBundle().getSymbolicName(); // IDynamicPropertyMap result = (IDynamicPropertyMap)prefs.get(id); // // if (result != null) { // return result; // } // // result = new PreferencesAdapter(toQuery.getPluginPreferences()); // prefs.put(id, result); // return result; // } /** * Move the tabs around. This is for testing ONLY. * @param part the part to move * @param index the new index * @since 3.2 */ void MoveTab(IPresentablePart::Pointer part, int index); /** * Get the tab list. This is for testing ONLY. * @return the presentable parts in order. * @since 3.2 */ QList GetPartList(); // /** // * Cause the folder to hide or show its // * Minimize and Maximize affordances. // * // * @param show // * true - the min/max buttons are visible. // * @since 3.3 // */ // void ShowMinMax(bool show) { // folder.getTabFolder().showMinMax(show); // } }; } #endif /* BERRYTABBEDSTACKPRESENTATION_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 e645b9a28f..0359d32cc9 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,268 @@ /*=================================================================== 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; + virtual void SetBounds(const QRect& 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 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/presentations/berryIStackPresentationSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIStackPresentationSite.h index 3a4b170188..56298d45cc 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIStackPresentationSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIStackPresentationSite.h @@ -1,193 +1,192 @@ /*=================================================================== 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 BERRYISTACKPRESENTATIONSITE_H_ #define BERRYISTACKPRESENTATIONSITE_H_ #include #include #include "berryIPresentablePart.h" #include -#include "berryPoint.h" namespace berry { /** * Represents the main interface between a StackPresentation and the workbench. * * Not intended to be implemented by clients. * * @since 3.0 * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IStackPresentationSite : public Object { berryObjectMacro(berry::IStackPresentationSite) static int STATE_MINIMIZED; // = 0; static int STATE_MAXIMIZED; // = 1; static int STATE_RESTORED; // = 2; ~IStackPresentationSite(); /** * Sets the state of the container. Called by the presentation when the * user causes the the container to be minimized, maximized, etc. * * @param newState one of the STATE_* constants */ virtual void SetState(int newState) = 0; /** * Returns the current state of the site (one of the STATE_* constants) * * @return the current state of the site (one of the STATE_* constants) */ virtual int GetState() = 0; /** * Returns true iff the site supports the given state * * @param state one of the STATE_* constants, above * @return true iff the site supports the given state */ virtual bool SupportsState(int state) = 0; /** * Begins dragging the given part * * @param beingDragged the part to drag (not null) * @param initialPosition the mouse position at the time of the initial mousedown * (display coordinates, not null) * @param keyboard true iff the drag was initiated via mouse dragging, * and false if the drag may be using the keyboard */ virtual void DragStart(IPresentablePart::Pointer beingDragged, - Point& initialPosition, bool keyboard) = 0; + QPoint& initialPosition, bool keyboard) = 0; /** * Closes the given set of parts. * * @param toClose the set of parts to close (Not null. All of the entries must be non-null) */ virtual void Close(const QList& toClose) = 0; /** * Begins dragging the entire stack of parts * * @param initialPosition the mouse position at the time of the initial mousedown (display coordinates, * not null) * @param keyboard true iff the drag was initiated via mouse dragging, * and false if the drag may be using the keyboard */ - virtual void DragStart(Point& initialPosition, bool keyboard) = 0; + virtual void DragStart(QPoint& initialPosition, bool keyboard) = 0; /** * Returns true iff this site will allow the given part to be closed * * @param toClose part to test (not null) * @return true iff the part may be closed */ virtual bool IsCloseable(IPresentablePart::Pointer toClose) = 0; /** * Returns true iff the given part can be dragged. If this * returns false, the given part should not trigger a drag. * * @param toMove part to test (not null) * @return true iff this part is a valid drag source */ virtual bool IsPartMoveable(IPresentablePart::Pointer toMove) = 0; /** * Returns true iff this entire stack can be dragged * * @return true iff the stack can be dragged */ virtual bool IsStackMoveable() = 0; /** * Makes the given part active * * @param toSelect */ virtual void SelectPart(IPresentablePart::Pointer toSelect) = 0; /** * Returns the currently selected part or null if the stack is empty * * @return the currently selected part or null if the stack is empty */ virtual IPresentablePart::Pointer GetSelectedPart() = 0; /** * Adds system actions to the given menu manager. The site may * make use of the following group ids: *
      *
    • close, for close actions
    • *
    • size, for resize actions
    • *
    • misc, for miscellaneous actions
    • *
    * The presentation can control the insertion position by creating * these group IDs where appropriate. * * @param menuManager the menu manager to populate */ //virtual void AddSystemActions(IMenuManager menuManager); /** * Notifies the workbench that the preferred size of the presentation has * changed. Hints to the workbench that it should trigger a layout at the * next opportunity. * * @since 3.1 */ virtual void FlushLayout() = 0; /** * Returns the list of presentable parts currently in this site * * @return the list of presentable parts currently in this site * @since 3.1 */ virtual QList GetPartList() = 0; /** * Returns the property with the given id or null. Folder * properties are an extensible mechanism for perspective authors to * customize the appearance of view stacks. The list of customizable * properties is determined by the presentation factory, and set in the * perspective factory. * * @param id * Must not be null. * @return property value, or null if the property is not * set. * @since 3.3 */ virtual QString GetProperty(const QString& id) = 0; }; } #endif /* BERRYISTACKPRESENTATIONSITE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.cpp index 76810d79f0..0c2967a395 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.cpp @@ -1,39 +1,39 @@ /*=================================================================== 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 "berryStackDropResult.h" namespace berry { -StackDropResult::StackDropResult(const Rectangle& snapRectangle, +StackDropResult::StackDropResult(const QRect& snapRectangle, Object::Pointer cookie) : snapRectangle(snapRectangle), cookie(cookie) { } -Rectangle StackDropResult::GetSnapRectangle() +QRect StackDropResult::GetSnapRectangle() { return snapRectangle; } Object::Pointer StackDropResult::GetCookie() { return cookie; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.h index 5c5243da34..20c38c5dd7 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackDropResult.h @@ -1,79 +1,81 @@ /*=================================================================== 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 BERRYSTACKDROPRESULT_H_ #define BERRYSTACKDROPRESULT_H_ #include #include -#include "berryRectangle.h" +#include + +#include namespace berry { /** * This structure describes a drop event that will cause a dragged part * to be stacked in a position currently occupied by another part. * */ class BERRY_UI_QT StackDropResult : public Object { public: - berryObjectMacro(StackDropResult); + berryObjectMacro(StackDropResult) private: - Rectangle snapRectangle; + QRect snapRectangle; Object::Pointer cookie; public: /** * Creates a drop result * * @param snapRectangle region that should be highlighted by the tracking * rectangle (display coordinates) * @param cookie the presentation may attach an object to this drop result * in order to identify the drop location. This object will be passed back into the * presentation's add method. */ - StackDropResult(const Rectangle& snapRectangle, Object::Pointer cookie); + StackDropResult(const QRect& snapRectangle, Object::Pointer cookie); /** * Returns a rectangle (screen coordinates) describing the target location * for this drop operation. While dragging, the tracking rectangle will * snap to this position. * * @return a snap rectangle (not null) */ - Rectangle GetSnapRectangle(); + QRect GetSnapRectangle(); /** * Returns the cookie for this drop result. This object provided by the presentation, * but is remembered by the workbench. It will be given back to the presentation's add * method to indicate that a part is being added as a result of a drop operation. * * @return the drop cookie for this drop result */ Object::Pointer GetCookie(); }; } #endif /* BERRYSTACKDROPRESULT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.cpp index e2eb648ff5..f1f18fe0a1 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.cpp @@ -1,105 +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. ===================================================================*/ #include "berryStackPresentation.h" #include "berryConstants.h" namespace berry { const int StackPresentation::AS_INACTIVE = 0; const int StackPresentation::AS_ACTIVE_FOCUS = 1; const int StackPresentation::AS_ACTIVE_NOFOCUS = 2; StackPresentation::StackPresentation(IStackPresentationSite::Pointer stackSite) : site(stackSite) { poco_assert(stackSite.IsNotNull()); } StackPresentation::~StackPresentation() { // Do not remove empty destructor. Otherwise, the WeakPointer member "site" // will be destroyed in a strange way and the destruction of a DefaultStackPresentationSite // instance will notify the WeakPointer "site" (although it was destroyed, the // DefaultStackPresentationSite somehow still has a MessageDelegate for the destroy // event, pointing to the destroyed "site"). } IStackPresentationSite::Pointer StackPresentation::GetSite() { return site.Lock(); } -Point StackPresentation::ComputeMinimumSize() +QSize StackPresentation::ComputeMinimumSize() { - return Point(0, 0); + return QSize(0, 0); } int StackPresentation::GetSizeFlags(bool /*width*/) { bool hasMaximumSize = this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED; return Constants::MIN | (hasMaximumSize ? Constants::MAX : 0); } int StackPresentation::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { - Point p = this->ComputeMinimumSize(); - int minSize = width ? p.x : p.y; + QSize s = this->ComputeMinimumSize(); + int minSize = width ? s.width() : s.width(); if (this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED || preferredResult < minSize) { return minSize; } return preferredResult; } void StackPresentation::MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie) { this->RemovePart(toMove); this->AddPart(toMove, cookie); if (this->GetSite()->GetSelectedPart() == toMove) { this->SelectPart(toMove); toMove->SetFocus(); } } void StackPresentation::SaveState(IPresentationSerializer* /*context*/, IMemento::Pointer /*memento*/) { } void StackPresentation::RestoreState(IPresentationSerializer* /*context*/, IMemento::Pointer /*memento*/) { } void StackPresentation::ShowPartList() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.h index 095b1a1155..d50856d686 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryStackPresentation.h @@ -1,275 +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. ===================================================================*/ #ifndef BERRYSTACKPRESENTATION_H_ #define BERRYSTACKPRESENTATION_H_ #include #include #include "berryIStackPresentationSite.h" #include "berryIPresentationSerializer.h" #include "berryStackDropResult.h" #include "berryISizeProvider.h" #include "berryIMemento.h" namespace berry { /** * This represents an object that can supply trim around a IPresentablePart. * Clients can implement subclasses to provide the appearance for editor workbooks, * view folders, fast views, and detached windows. *

    * StackPresentations do not store any persistent state and cannot * directly make changes to the workbench. They are given an IStackPresentationSite * reference on creation, which allows them to send events and requests to the workbench. * However, the workbench is free to ignore these requests. The workbench will call one * of the public methods on StackPresentation when (and if) the presentation is expected to * change state. *

    *

    * For example, if the user clicks a button that is intended to close a part, the * StackPresentation will send a close request to its site, but should not assume * that the part has been closed until the workbench responds with a call * StackPresentation.remove. *

    * * @since 3.0 */ class BERRY_UI_QT StackPresentation : public Object, public ISizeProvider { public: - berryObjectMacro(StackPresentation); + berryObjectMacro(StackPresentation) private: /** * The presentation site. */ IStackPresentationSite::WeakPtr site; protected: /** * Constructs a new stack presentation with the given site. * * @param stackSite the stack site */ StackPresentation(IStackPresentationSite::Pointer stackSite); ~StackPresentation(); /** * Returns the presentation site (not null). * @return IStackPresentationSite */ IStackPresentationSite::Pointer GetSite(); public: /** * Inactive state. This is the default state for deselected presentations. */ static const int AS_INACTIVE; // = 0; /** * Activation state indicating that one of the parts in the presentation currently has focus */ static const int AS_ACTIVE_FOCUS; // = 1; /** * Activation state indicating that none of the parts in the presentation have focus, but * one of the parts is being used as the context for global menus and toolbars */ static const int AS_ACTIVE_NOFOCUS; // = 2; /** * Sets the bounding rectangle for this presentation. * * @param bounds new bounding rectangle (not null) */ - virtual void SetBounds(const Rectangle& bounds) = 0; + virtual void SetBounds(const QRect& bounds) = 0; /** * Returns the minimum size for this stack. The stack is prevented * from being resized smaller than this amount, and this is used as * the default size for the stack when it is minimized. Typically, * this is the amount of space required to fit the minimize, close, * and maximize buttons and one tab. * * @return the minimum size for this stack (not null) * * @deprecated replaced by computePreferredSize */ - virtual Point ComputeMinimumSize(); + virtual QSize ComputeMinimumSize(); /* * @see ISizeProvider#getSizeFlags(boolean) */ virtual int GetSizeFlags(bool width); /* * @see ISizeProvider#computePreferredSize(boolean, int, int, int) */ virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); /** * This is invoked to notify the presentation that its activation * state has changed. StackPresentations can have three possible activation * states (see the AS_* constants above) * * @param newState one of AS_INACTIVE, AS_ACTIVE, or AS_ACTIVE_NOFOCUS */ virtual void SetActive(int newState) = 0; /** * This causes the presentation to become visible or invisible. * When a presentation is invisible, it must not respond to user * input or modify its parts. For example, a presentations will * be made invisible if it belongs to a perspective and the user * switches to another perspective. * * @param isVisible the state to set visibility to * * @since 3.0 */ virtual void SetVisible(bool isVisible) = 0; /** * Sets the state of the presentation. That is, notifies the presentation * that is has been minimized, maximized, or restored. Note that this method * is the only way that a presentation is allowed to change its state. *

    * If a presentation wishes to minimize itself, it must call setState * on its associated IStackPresentationSite. If the site chooses to respond * to the state change, it will call this method at the correct time. * The presentation should not call this method directly. *

    * * @param state one of the IStackPresentationSite.STATE_* constants. */ virtual void SetState(int state) = 0; /** * Returns the control for this presentation * * @return the control for this presentation (not null) */ virtual void* GetControl() = 0; /** * Adds the given part to the stack. The presentation is free to determine * where the part should be inserted. If the part is being inserted as the * result of a drag/drop operation, it will be given a cookie * identifying the drop location. Has no effect if an identical part is * already in the presentation. * * @param newPart the new part to add (not null) * @param cookie an identifier for a drop location, or null. When the presentation * attaches a cookie to a StackDropResult, that cookie is passed back into * addPart when a part is actually dropped in that location. */ virtual void AddPart(IPresentablePart::Pointer newPart, Object::Pointer cookie) = 0; /** * Removes the given part from the stack. * * @param oldPart the part to remove (not null) */ virtual void RemovePart(IPresentablePart::Pointer oldPart) = 0; /** * Moves a part to a new location as the result of a drag/drop * operation within this presentation. * * @param toMove a part that already belongs to this presentation * @param cookie a drop cookie returned by StackPresentation#dragOver * @since 3.1 */ virtual void MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie); /** * Brings the specified part to the foreground. This should not affect * the current focus. * * @param toSelect the new active part (not null) */ virtual void SelectPart(IPresentablePart::Pointer toSelect) = 0; /** * This method is invoked whenever a part is dragged over the stack's control. * It returns a StackDropResult if and only if the part may be dropped in this * location. * * @param currentControl the control being dragged over * @param location cursor location (display coordinates) * @return a StackDropResult or null if the presentation does not have * a drop target in this location. */ - virtual StackDropResult::Pointer DragOver(void* currentControl, const Point& location) = 0; + virtual StackDropResult::Pointer DragOver(void* currentControl, const QPoint& location) = 0; /** * Instructs the presentation to display the system menu * */ // virtual void ShowSystemMenu() = 0; /** * Instructs the presentation to display the pane menu */ // virtual void ShowPaneMenu() = 0; /** * Instructs the presentation to display a list of all parts in the stack, and * allow the user to change the selection using the keyboard. */ virtual void ShowPartList(); /** * Saves the state of this presentation to the given memento. * * @param context object that can be used to generate unique IDs for IPresentableParts (this * may be a temporary object - the presentation should not keep any references to it) * @param memento memento where the data will be saved */ virtual void SaveState(IPresentationSerializer* context, IMemento::Pointer memento); /** * Restores the state of this presentation to a previously saved state. * * @param context object that can be used to find IPresentableParts given string IDs (this * may be a temporary object - the presentation should not keep any references to it) * @param memento memento where the data will be saved */ virtual void RestoreState(IPresentationSerializer* context, IMemento::Pointer memento); /** * Returns the tab-key traversal order for the given IPresentablePart. * * @param part the part * @return the tab-key traversal order */ virtual QList GetTabList(IPresentablePart::Pointer part) = 0; }; } #endif /* BERRYSTACKPRESENTATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.cpp deleted file mode 100755 index f8b377de5a..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.cpp +++ /dev/null @@ -1,64 +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 "berryDnDTweaklet.h" - -#include "berryConstants.h" - -namespace berry -{ - -Tweaklets::TweakKey DnDTweaklet::KEY = - Tweaklets::TweakKey(); - -DnDTweaklet::CursorType DnDTweaklet::PositionToCursorType(int positionConstant) -{ - if (positionConstant == Constants::LEFT) - return CURSOR_LEFT; - if (positionConstant == Constants::RIGHT) - return CURSOR_RIGHT; - if (positionConstant == Constants::TOP) - return CURSOR_TOP; - if (positionConstant == Constants::BOTTOM) - return CURSOR_BOTTOM; - if (positionConstant == Constants::CENTER) - return CURSOR_CENTER; - - - return CURSOR_INVALID; -} - -int DnDTweaklet::CursorTypeToPosition(CursorType dragCursorId) -{ - switch (dragCursorId) - { - case CURSOR_LEFT: - return Constants::LEFT; - case CURSOR_RIGHT: - return Constants::RIGHT; - case CURSOR_TOP: - return Constants::TOP; - case CURSOR_BOTTOM: - return Constants::BOTTOM; - case CURSOR_CENTER: - return Constants::CENTER; - default: - return Constants::DEFAULT; - } -} - -} - diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.h deleted file mode 100755 index b393a50579..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryDnDTweaklet.h +++ /dev/null @@ -1,67 +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 BERRYDNDTWEAKLET_H_ -#define BERRYDNDTWEAKLET_H_ - -#include - -#include -#include "internal/berryTweaklets.h" - -namespace berry -{ - -struct ITracker; - -/** - * Provides the set of cursors used for drag-and-drop. - */ -struct BERRY_UI_QT DnDTweaklet -{ - - static Tweaklets::TweakKey KEY; - - enum CursorType - { CURSOR_INVALID, - CURSOR_LEFT, - CURSOR_RIGHT, - CURSOR_TOP, - CURSOR_BOTTOM, - CURSOR_CENTER, - CURSOR_OFFSCREEN, - CURSOR_FASTVIEW}; - - static CursorType PositionToCursorType(int positionConstant); - - /** - * Converts a DnDTweaklet::CursorType (CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER) into a BlueBerry constant - * (Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM, Constants::CENTER) - * - * @param dragCursorId - * @return a BlueBerry Constants::* constant - */ - static int CursorTypeToPosition(CursorType dragCursorId); - - virtual ITracker* CreateTracker() = 0; - -}; - -} - -Q_DECLARE_INTERFACE(berry::DnDTweaklet, "org.blueberry.DnDTweaklet") - -#endif /* BERRYDNDTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h index 811371a03d..197b1c2051 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h @@ -1,211 +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. ===================================================================*/ #ifndef BERRYGUIWIDGETSTWEAKLET_H_ #define BERRYGUIWIDGETSTWEAKLET_H_ #include "internal/berryTweaklets.h" #include "guitk/berryGuiTkISelectionListener.h" #include "guitk/berryGuiTkIControlListener.h" -#include "berryRectangle.h" #include "berryShell.h" //#include "commands/berryIMenu.h" //#include "commands/berryIMenuItem.h" namespace berry { struct BERRY_UI_QT GuiWidgetsTweaklet { static Tweaklets::TweakKey KEY; virtual void AddSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; virtual void RemoveSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; /** * Adds the listener to the collection of listeners who will * be notified when the widget is moved or resized, by sending * it one of the messages defined in the IControlListener * interface. * * @param listener the listener which should be notified * * @see IControlListener * @see #RemoveControlListener */ virtual void AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; /** * Removes the listener from the collection of listeners who will * be notified when the widget is moved or resized. * * @param listener the listener which should no longer be notified * * @see IControlListener * @see #AddControlListener */ virtual void RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; virtual bool GetEnabled(void* widget) = 0; virtual void SetEnabled(void* widget, bool enabled) = 0; - virtual void SetBounds(void* widget, const Rectangle& bounds) = 0; - virtual Rectangle GetBounds(void* widget) = 0; + virtual void SetBounds(void* widget, const QRect& bounds) = 0; + virtual QRect GetBounds(void* widget) = 0; virtual void SetVisible(void* widget, bool visible) = 0; virtual bool GetVisible(void* widget) = 0; virtual bool IsVisible(void* widget) = 0; - virtual Rectangle GetClientArea(void* widget) = 0; + virtual QRect GetClientArea(void* widget) = 0; virtual void* GetParent(void* widget) = 0; virtual bool SetParent(void* widget, void* parent) = 0; virtual void SetData(void* widget, const QString& id, Object::Pointer data) = 0; virtual Object::Pointer GetData(void* widget, const QString& id) = 0; - virtual Point GetCursorLocation() = 0; + virtual QPoint GetCursorLocation() = 0; virtual void* GetCursorControl() = 0; - virtual void* FindControl(const QList& shells, const Point& location) = 0; + virtual void* FindControl(const QList& shells, const QPoint& location) = 0; /** * Determines if one control is a child of another. Returns true iff the second * argument is a child of the first (or the same object). * * @param potentialParent * @param childToTest * @return */ virtual bool IsChild(void* potentialParent, void* childToTest) = 0; /** * Returns the control which currently has keyboard focus, * or null if keyboard events are not currently going to * any of the controls built by the currently running * application. * * @return the control under the cursor */ virtual void* GetFocusControl() = 0; virtual bool IsReparentable(void* widget) = 0; virtual void MoveAbove(void* widgetToMove, void* widget) = 0; virtual void MoveBelow(void* widgetToMove, void* widget) = 0; virtual void Dispose(void* widget) = 0; virtual Shell::Pointer CreateShell(Shell::Pointer parent, int style) = 0; virtual void DisposeShell(Shell::Pointer shell) = 0; virtual void* CreateComposite(void* parent) = 0; virtual QList GetShells() = 0; virtual Shell::Pointer GetShell(void* widget) = 0; virtual Shell::Pointer GetActiveShell() = 0; // command framework interface classes //virtual IMenu::Pointer CreateMenu(void*, IMenu::Style = IMenu::POP_UP) = 0; //virtual IMenu::Pointer CreateMenu(IMenu::Pointer parent) = 0; //virtual IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1) = 0; /** * @brief returns the coordinates of the center point of the primary screen * (where the application starts) of the current desktop. * * @param i the number of the screen (if there are multiple). If i = -1 * a rectangle representing the size of the virtual desktop is returned. * @return the screen Geometry. * @see GetScreenNumber() * @see GetPrimaryScreenNumber() */ - virtual Rectangle GetScreenSize(int i = -1) = 0; + virtual QRect GetScreenSize(int i = -1) = 0; - virtual Rectangle GetAvailableScreenSize(int i = -1) = 0; + virtual QRect GetAvailableScreenSize(int i = -1) = 0; - virtual int GetClosestScreenNumber(const Rectangle&) = 0; + virtual int GetClosestScreenNumber(const QRect&) = 0; /** * @brief Gets the number of available screens in a multi-screen environment. * * @return the number of available screens in a multi-screen environment. */ virtual unsigned int GetScreenNumber() = 0; /** * @brief Gets the number of the primary screen. * * @return the number of the primary screen. */ virtual int GetPrimaryScreenNumber() = 0; /** * Converts the given rectangle from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert rectangle to convert * @return a rectangle in control coordinates * @since 3.0 */ - virtual Rectangle ToControl(void* coordinateSystem, - const Rectangle& toConvert) = 0; + virtual QRect ToControl(void* coordinateSystem, + const QRect& toConvert) = 0; /** * Converts the given point from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert point to convert * @return a point in control coordinates * @since 3.0 */ - virtual Point ToControl(void* coordinateSystem, - const Point& toConvert) = 0; + virtual QPoint ToControl(void* coordinateSystem, + const QPoint& toConvert) = 0; /** * Converts the given rectangle from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert rectangle to convert * @return a rectangle in display coordinates * @since 3.0 */ - virtual Rectangle ToDisplay(void* coordinateSystem, - const Rectangle& toConvert) = 0; + virtual QRect ToDisplay(void* coordinateSystem, + const QRect& toConvert) = 0; /** * Converts the given point from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert point to convert * @return a point in display coordinates * @since 3.0 */ - virtual Point ToDisplay(void* coordinateSystem, - const Point& toConvert) = 0; + virtual QPoint ToDisplay(void* coordinateSystem, + const QPoint& toConvert) = 0; }; } Q_DECLARE_INTERFACE(berry::GuiWidgetsTweaklet, "org.blueberry.GuiWidgetsTweaklet") #endif /* BERRYGUIWIDGETSTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.cpp deleted file mode 100644 index cdcf25895f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.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 "berryITracker.h" - -namespace berry -{ - -ITracker::~ITracker() -{ -} -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.h deleted file mode 100755 index e5ebe9f86f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryITracker.h +++ /dev/null @@ -1,55 +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 BERRYITRACKER_H_ -#define BERRYITRACKER_H_ - -#include "berryDnDTweaklet.h" - -#include "berryRectangle.h" -#include "guitk/berryGuiTkIControlListener.h" - -namespace berry { - -/** - * Instances of this class implement a rubber banding rectangle that is - * drawn onto a parent control or display. - * These rectangles can be specified to respond to mouse and key events - * by either moving or resizing themselves accordingly. Trackers are - * typically used to represent window geometries in a lightweight manner. - * - */ -struct BERRY_UI_QT ITracker -{ - - virtual ~ITracker(); - - virtual Rectangle GetRectangle() = 0; - virtual void SetRectangle(const Rectangle& rectangle) = 0; - - virtual void SetCursor(DnDTweaklet::CursorType cursor) = 0; - - virtual bool Open() = 0; - - virtual void AddControlListener(GuiTk::IControlListener::Pointer listener) = 0; - virtual void RemoveControlListener(GuiTk::IControlListener::Pointer listener) = 0; - -}; - -} - -#endif /* BERRYITRACKER_H_ */ diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp index 9737734db4..50ccdc2372 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp @@ -1,81 +1,83 @@ /*=================================================================== 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. ===================================================================*/ #include "ExtensionPointDefinition.h" // berry Includes #include #include +#include + class MinimalWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size - configurer->SetInitialSize(berry::Point(600,400)); + configurer->SetInitialSize(QPoint(600,400)); // Set an individual title configurer->SetTitle("Extension Points"); // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(false); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; const QString MinimalWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; ExtensionPointDefinition::ExtensionPointDefinition() { } ExtensionPointDefinition::~ExtensionPointDefinition() { } int ExtensionPointDefinition::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MinimalWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void ExtensionPointDefinition::Stop() { //nothing to do } diff --git a/Examples/Plugins/org.mitk.example.gui.minimalapplication/src/internal/MinimalApplication.cpp b/Examples/Plugins/org.mitk.example.gui.minimalapplication/src/internal/MinimalApplication.cpp index 30e1aeea52..7c2a5fae2c 100644 --- a/Examples/Plugins/org.mitk.example.gui.minimalapplication/src/internal/MinimalApplication.cpp +++ b/Examples/Plugins/org.mitk.example.gui.minimalapplication/src/internal/MinimalApplication.cpp @@ -1,75 +1,77 @@ /*=================================================================== 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. ===================================================================*/ #include "MinimalApplication.h" // Berry #include #include +#include + class MinimalWorkbenchAdvisor : public berry::WorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size - configurer->SetInitialSize(berry::Point(600,400)); + configurer->SetInitialSize(QPoint(600,400)); // Set an individual title configurer->SetTitle("Minimal Application"); // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(false); return new berry::WorkbenchWindowAdvisor(configurer); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } }; const QString MinimalWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; MinimalApplication::MinimalApplication() { } MinimalApplication::~MinimalApplication() { } int MinimalApplication::Start() { QScopedPointer display(berry::PlatformUI::CreateDisplay()); QScopedPointer wbAdvisor(new MinimalWorkbenchAdvisor()); int code = berry::PlatformUI::CreateAndRunWorkbench(display.data(), wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void MinimalApplication::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp index 682f20ddc0..589e4846f9 100644 --- a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp +++ b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp @@ -1,86 +1,88 @@ /*=================================================================== 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. ===================================================================*/ #include "MultiplePerspectives.h" // berry includes #include #include +#include + class MultiplePerspectivesWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { //! [initial window size] // Set an individual initial size - configurer->SetInitialSize(berry::Point(600,400)); + configurer->SetInitialSize(QPoint(600,400)); //! [initial window size] // Set an individual title configurer->SetTitle("Multiple Perspectives"); //! [Visibility of perspective bar] // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(true); //! [Visibility of perspective bar] wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; const QString MultiplePerspectivesWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; MultiplePerspectives::MultiplePerspectives() { } MultiplePerspectives::~MultiplePerspectives() { } int MultiplePerspectives::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MultiplePerspectivesWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void MultiplePerspectives::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp index 9b95cb22b8..f9a1603e76 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp @@ -1,78 +1,80 @@ /*=================================================================== 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. ===================================================================*/ #include "SelectionServiceMitk.h" // berry includes #include #include +#include + class SelectionServiceMITKWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size - configurer->SetInitialSize(berry::Point(600,400)); + configurer->SetInitialSize(QPoint(600,400)); // Set the window title configurer->SetTitle("MITK Selection Service"); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; const QString SelectionServiceMITKWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceMitk::SelectionServiceMitk() { } SelectionServiceMitk::~SelectionServiceMitk() { } int SelectionServiceMitk::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceMITKWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceMitk::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp index d8b9a85f8d..396f553bd4 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp @@ -1,78 +1,80 @@ /*=================================================================== 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. ===================================================================*/ #include "SelectionServiceQt.h" // berry includes #include #include +#include + class SelectionServiceQtWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size - configurer->SetInitialSize(berry::Point(600,400)); + configurer->SetInitialSize(QPoint(600,400)); // Set the window title configurer->SetTitle("Qt Selection Service"); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; const QString SelectionServiceQtWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceQt::SelectionServiceQt() { } SelectionServiceQt::~SelectionServiceQt() { } int SelectionServiceQt::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceQtWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceQt::Stop() { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp index 6caabbed42..b03b3b1bfe 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp @@ -1,100 +1,101 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (cGerman 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 "QmitkDTIAtlasAppWorkbenchAdvisor.h" #include "internal/QmitkDTIAtlasAppApplicationPlugin.h" #include #include #include #include #include #include +#include const QString QmitkDTIAtlasAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.dtiatlasapp.perspectives.welcome"; void QmitkDTIAtlasAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); // TODO This should go into the products plugin_customization.ini file (when // the product and branding support is finished, see bug 2146). // This will not work anymore, if bug 2822 is fixed. berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); prefService->GetSystemPreferences()->Put(berry::WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, berry::WorkbenchPreferenceConstants::RIGHT); } berry::WorkbenchWindowAdvisor* QmitkDTIAtlasAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QList perspExcludeList; perspExcludeList.push_back( "org.mitk.dtiatlasapp.perspectives.welcome"); perspExcludeList.push_back( "org.mitk.perspectives.diffusionimaginginternal"); perspExcludeList.push_back( "org.mitk.perspectives.publicdiffusionimaging"); perspExcludeList.push_back( "org.mitk.extapp.defaultperspective"); perspExcludeList.push_back( "org.mitk.coreapp.defaultperspective"); QList viewExcludeList; viewExcludeList.push_back( "org.mitk.views.partialvolumeanalysis"); viewExcludeList.push_back( "org.mitk.views.globalfibertracking"); viewExcludeList.push_back( "org.mitk.views.tractbasedspatialstatistics"); viewExcludeList.push_back( "org.mitk.views.fibertracking"); viewExcludeList.push_back( "org.mitk.views.ivim"); viewExcludeList.push_back( "org.mitk.views.qballreconstruction"); viewExcludeList.push_back( "org.mitk.views.diffusiondicomimport"); viewExcludeList.push_back( "org.mitk.views.diffusionpreprocessing"); viewExcludeList.push_back( "org.mitk.views.diffusionquantification"); viewExcludeList.push_back( "org.mitk.views.tensorreconstruction"); viewExcludeList.push_back( "org.mitk.views.perspectiveswitcher"); viewExcludeList.push_back( "org.mitk.views.basicimageprocessing"); viewExcludeList.push_back( "org.mitk.views.fiberbundleoperations"); viewExcludeList.push_back( "org.mitk.views.measurement"); viewExcludeList.push_back( "org.mitk.views.moviemaker"); viewExcludeList.push_back( "org.mitk.views.odfdetails"); viewExcludeList.push_back( "org.mitk.views.properties"); viewExcludeList.push_back( "org.mitk.views.screenshotmaker"); viewExcludeList.push_back( "org.mitk.views.segmentation"); viewExcludeList.push_back( "org.mitk.views.imagestatistics"); // viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview"); viewExcludeList.push_back( "org.mitk.views.volumevisualization"); viewExcludeList.push_back( "org.mitk.views.simplemeasurement"); configurer->SetShowPerspectiveBar(false); - configurer->SetInitialSize(berry::Point(1000,770)); + configurer->SetInitialSize(QPoint(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->SetProductName("based on MITK Diffusion Imaging App"); advisor->SetWindowIcon(":/org.mitk.gui.qt.dtiatlasapp/app-icon.png"); return advisor; } QString QmitkDTIAtlasAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; }