diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp index a64c6484a7..50bdd9e9a3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,144 +1,144 @@ /*=================================================================== 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 "berryWorkbenchWindowAdvisor.h" #include #include #include #include #include #include #include #include "internal/berryWorkbenchWindowConfigurer.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer() { return windowConfigurer; } WorkbenchWindowAdvisor::WorkbenchWindowAdvisor( const IWorkbenchWindowConfigurer::Pointer& configurer) { poco_assert(configurer.IsNotNull()); this->windowConfigurer = configurer; } WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor() { } void WorkbenchWindowAdvisor::PreWindowOpen() { // do nothing } ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer) { ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer)); return actionBarAdvisor; } void WorkbenchWindowAdvisor::PostWindowRestore() { // do nothing } void WorkbenchWindowAdvisor::OpenIntro() { // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call // introOpened flag needs to be global IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer(); QString key = "introOpened"; //$NON-NLS-1$ ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast(); if (introOpened && introOpened->GetValue()) { return; } wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true))); IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true); IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager(); bool hasIntro = introManager->HasIntro(); bool isNewIntroContentAvailable = introManager->IsNewContentAvailable(); if (hasIntro && (showIntro || isNewIntroContentAvailable)) { introManager ->ShowIntro(GetWindowConfigurer()->GetWindow(), false); workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } } void WorkbenchWindowAdvisor::PostWindowCreate() { // do nothing } void WorkbenchWindowAdvisor::PostWindowOpen() { // do nothing } bool WorkbenchWindowAdvisor::PreWindowShellClose() { // do nothing, but allow the close() to proceed return true; } void WorkbenchWindowAdvisor::PostWindowClose() { // do nothing } void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell) { this->GetWindowConfigurer().Cast()->CreateDefaultContents(shell); } -void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void* /*parent*/) +QWidget* WorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* /*parent*/) { return 0; } bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer /*memento*/) { // do nothing return true; } bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer /*memento*/) { // do nothing return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h index ac951e9a8b..f72037ee78 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.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 BERRYWORKBENCHWINDOWADVISOR_H_ #define BERRYWORKBENCHWINDOWADVISOR_H_ #include #include namespace berry { struct IActionBarConfigurer; struct IMemento; struct IWorkbenchWindowConfigurer; class ActionBarAdvisor; class Shell; /** * Public base class for configuring a workbench window. *

* The workbench window advisor object is created in response to a workbench * window being created (one per window), and is used to configure the window. *

*

* An application should declare a subclass of WorkbenchWindowAdvisor * and override methods to configure workbench windows to suit the needs of the * particular application. *

*

* The following advisor methods are called at strategic points in the * workbench window's lifecycle (as with the workbench advisor, all occur * within the dynamic scope of the call to * PlatformUI#CreateAndRunWorkbench()): *

    *
  • PreWindowOpen() - called as the window is being opened; * use to configure aspects of the window other than actions bars
  • *
  • PostWindowRestore() - called after the window has been * recreated from a previously saved state; use to adjust the restored * window
  • *
  • PostWindowCreate() - called after the window has been created, * either from an initial state or from a restored state; used to adjust the * window
  • *
  • OpenIntro() - called immediately before the window is opened in * order to create the introduction component, if any.
  • *
  • PostWindowOpen() - called after the window has been * opened; use to hook window listeners, etc.
  • *
  • PreWindowShellClose() - called when the window's shell * is closed by the user; use to pre-screen window closings
  • *
*

* */ class BERRY_UI_QT WorkbenchWindowAdvisor { private: SmartPointer windowConfigurer; protected: /** * Returns the workbench window configurer. * * @return the workbench window configurer */ SmartPointer GetWindowConfigurer(); public: /** * Creates a new workbench window advisor for configuring a workbench * window via the given workbench window configurer. * * @param configurer an object for configuring the workbench window */ WorkbenchWindowAdvisor(const SmartPointer& configurer); virtual ~WorkbenchWindowAdvisor(); /** * Performs arbitrary actions before the window is opened. *

* This method is called before the window's controls have been created. * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. * Typical clients will use the window configurer to tweak the * workbench window in an application-specific way; however, filling the * window's menu bar, tool bar, and status line must be done in * ActionBarAdvisor#FillActionBars(), which is called immediately * after this method is called. *

*/ virtual void PreWindowOpen(); /** * Creates a new action bar advisor to configure the action bars of the window * via the given action bar configurer. * The default implementation returns a new instance of ActionBarAdvisor. * * @param configurer the action bar configurer for the window * @return the action bar advisor for the window */ virtual SmartPointer CreateActionBarAdvisor( SmartPointer configurer); /** * Performs arbitrary actions after the window has been restored, * but before it is opened. *

* This method is called after a previously-saved window has been * recreated. This method is not called when a new window is created from * scratch. This method is never called when a workbench is started for the * very first time, or when workbench state is not saved or restored. * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. * It is okay to call IWorkbench#Close() from this method. *

* * @exception WorkbenchException thrown if there are any errors to report * from post-restoration of the window */ virtual void PostWindowRestore(); /** * Opens the introduction componenet. *

* Clients must not call this method directly (although super calls are okay). * The default implementation opens the intro in the first window provided * if the preference WorkbenchPreferenceConstants#SHOW_INTRO is true. If * an intro is shown then this preference will be set to false. * Subsequently, and intro will be shown only if * WorkbenchConfigurer#GetSaveAndRestore() returns * true and the introduction was visible on last shutdown. * Subclasses may override. *

*/ virtual void OpenIntro(); /** * Performs arbitrary actions after the window has been created (possibly * after being restored), but has not yet been opened. *

* This method is called after the window has been created from scratch, * or when it has been restored from a previously-saved window. In the latter case, * this method is called after PostWindowRestore(). * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowCreate(); /** * Performs arbitrary actions after the window has been opened (possibly * after being restored). *

* This method is called after the window has been opened. This method is * called after the window has been created from scratch, or when * it has been restored from a previously-saved window. * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowOpen(); /** * Performs arbitrary actions as the window's shell is being closed * directly, and possibly veto the close. *

* This method is called from a IShellListener associated with the window, * for example when the user clicks the window's close button. It is not * called when the window is being closed for other reasons, such as if the * user exits the workbench via the ActionFactory#QUIT action. * Clients must not call this method directly (although super calls are * okay). If this method returns false, then the user's * request to close the shell is ignored. This gives the workbench advisor * an opportunity to query the user and/or veto the closing of a window * under some circumstances. *

* * @return true to allow the window to close, and * false to prevent the window from closing * @see IWorkbenchWindow#Close() * @see WorkbenchAdvisor#PreShutdown() */ virtual bool PreWindowShellClose(); /** * Performs arbitrary actions after the window is closed. *

* This method is called after the window's controls have been disposed. * Clients must not call this method directly (although super calls are * okay). The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowClose(); /** * Creates the contents of the window. *

* The default implementation adds a menu bar, a cool bar, a status line, * a perspective bar, and a fast view bar. The visibility of these controls * can be configured using the SetShow* methods on * IWorkbenchWindowConfigurer. *

*

* Subclasses may override to define custom window contents and layout, * but must call IWorkbenchWindowConfigurer#CreatePageComposite(). *

* * @param shell the window's shell * @see IWorkbenchWindowConfigurer#CreateMenuBar() * @see IWorkbenchWindowConfigurer#CreateCoolBarControl() * @see IWorkbenchWindowConfigurer#CreateStatusLineControl() * @see IWorkbenchWindowConfigurer#CreatePageComposite() */ virtual void CreateWindowContents(SmartPointer shell); /** * Creates and returns the control to be shown when the window has no open pages. * If null is returned, the default window background is shown. *

* The default implementation returns null. * Subclasses may override. *

* * @param parent the parent composite * @return the control or null */ - virtual void* CreateEmptyWindowContents(void* parent); + virtual QWidget* CreateEmptyWindowContents(QWidget* parent); /** * Saves arbitrary application specific state information. * * @param memento the storage area for object's state * @return a status object indicating whether the save was successful */ virtual bool SaveState(SmartPointer memento); /** * Restores arbitrary application specific state information. * * @param memento the storage area for object's state * @return a status object indicating whether the restore was successful */ virtual bool RestoreState(SmartPointer memento); }; } #endif /*BERRYWORKBENCHWINDOWADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp index 59cb93cfec..d2474b7394 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.cpp @@ -1,169 +1,166 @@ /*=================================================================== 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 #include namespace berry { int Geometry::GetDimension(const QRect& toMeasure, bool width) { if (width) { return toMeasure.width(); } return toMeasure.height(); } bool Geometry::IsHorizontal(int berrySideConstant) { return !(berrySideConstant == Constants::LEFT || berrySideConstant == Constants::RIGHT); } QRect Geometry::GetExtrudedEdge(const QRect& toExtrude, int size, int orientation) { QRect bounds(toExtrude); if (!IsHorizontal(orientation)) { bounds.setWidth(size); } else { bounds.setHeight(size); } if (orientation == Constants::RIGHT) { bounds.moveLeft(toExtrude.x() + toExtrude.width() - bounds.width()); } else if (orientation == Constants::BOTTOM) { bounds.moveTop(toExtrude.y() + toExtrude.height() - bounds.height()); } Normalize(bounds); return bounds; } void Geometry::Normalize(QRect& rect) { if (rect.width() < 0) { rect.setWidth(-rect.width()); rect.setX(-rect.width()); } if (rect.height() < 0) { rect.setHeight(-rect.height()); rect.setY(-rect.height()); } } 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 QRect& rectangle, const QPoint& testPoint, int edgeOfInterest) { if (edgeOfInterest == Constants::TOP) return testPoint.y() - rectangle.y(); else if (edgeOfInterest == Constants::BOTTOM) return rectangle.y() + rectangle.height() - testPoint.y(); else if (edgeOfInterest == Constants::LEFT) return testPoint.x() - rectangle.x(); else if (edgeOfInterest == Constants::RIGHT) 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; } -QRect Geometry::ToControl(void* coordinateSystem, +QRect Geometry::ToControl(QWidget* coordinateSystem, const QRect& toConvert) { - return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, - toConvert); + return QRect(coordinateSystem->mapFromGlobal(toConvert.topLeft()), + coordinateSystem->mapFromGlobal(toConvert.bottomRight())); } -QPoint Geometry::ToControl(void* coordinateSystem, const QPoint& toConvert) +QPoint Geometry::ToControl(QWidget* coordinateSystem, const QPoint& toConvert) { - return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, - toConvert); + return coordinateSystem->mapFromGlobal(toConvert); } -QRect Geometry::ToDisplay(void* coordinateSystem, +QRect Geometry::ToDisplay(QWidget* coordinateSystem, const QRect& toConvert) { - return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, - toConvert); + return QRect(coordinateSystem->mapToGlobal(toConvert.topLeft()), + coordinateSystem->mapToGlobal(toConvert.bottomRight())); } -QPoint Geometry::ToDisplay(void* coordinateSystem, const QPoint& toConvert) +QPoint Geometry::ToDisplay(QWidget* coordinateSystem, const QPoint& toConvert) { - return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, - toConvert); + return coordinateSystem->mapToGlobal(toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h index ee0c453512..41572807fd 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryGeometry.h @@ -1,165 +1,166 @@ /*=================================================================== 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 class QRect; class QPoint; +class QWidget; 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 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 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(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 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 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 QRect ToControl(void* coordinateSystem, + static QRect ToControl(QWidget* 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 QPoint ToControl(void* coordinateSystem, + static QPoint ToControl(QWidget* 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 QRect ToDisplay(void* coordinateSystem, + static QRect ToDisplay(QWidget* 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 QPoint ToDisplay(void* coordinateSystem, + static QPoint ToDisplay(QWidget* coordinateSystem, const QPoint& toConvert); }; } #endif /* BERRYGEOMETRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h index 74a07dc062..c06b63bfb3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h @@ -1,270 +1,270 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef IWORKBENCHPART_H_ #define IWORKBENCHPART_H_ #include #include "berryIPropertyChangeListener.h" #include namespace berry { struct IWorkbenchPartSite; /** * \ingroup org_blueberry_ui_qt * * A workbench part is a visual component within a workbench page. There * are two subtypes: view and editor, as defined by IViewPart and * IEditorPart. *

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

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

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

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

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

*

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

*

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

*

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

*

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

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

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

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

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

*

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

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

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

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

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

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

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

* A default implementation has been added to WorkbenchPart. *

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

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

*/ virtual void SetFocus() = 0; }; } // namespace berry #endif /*IWORKBENCHPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.cpp index 2f439e8f81..cf322a3b2e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.cpp @@ -1,27 +1,27 @@ /*=================================================================== 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 "berryQtEditorPart.h" namespace berry { -void QtEditorPart::CreatePartControl(void* parent) +void QtEditorPart::CreatePartControl(QWidget* parent) { this->CreateQtPartControl(static_cast(parent)); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h index 6f0f3e59d5..2938b63b49 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h @@ -1,42 +1,42 @@ /*=================================================================== 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 BERRYQTEDITORPART_H_ #define BERRYQTEDITORPART_H_ #include #include #include namespace berry { class BERRY_UI_QT QtEditorPart : public EditorPart { public: - berryObjectMacro(QtEditorPart); + berryObjectMacro(QtEditorPart) - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); protected: virtual void CreateQtPartControl(QWidget* parent) = 0; }; } #endif /*BERRYQTEDITORPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.cpp index 481367cdaf..ade1706091 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.cpp @@ -1,27 +1,27 @@ /*=================================================================== 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 "berryQtViewPart.h" namespace berry { -void QtViewPart::CreatePartControl(void* parent) +void QtViewPart::CreatePartControl(QWidget* parent) { this->CreateQtPartControl(static_cast(parent)); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.h index 3b3f39d58b..f9c4b73ed8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtViewPart.h @@ -1,53 +1,53 @@ /*=================================================================== 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 BERRYQTVIEWPART_H_ #define BERRYQTVIEWPART_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include namespace berry { class BERRY_UI_QT QtViewPart : public ViewPart { public: - berryObjectMacro(QtViewPart); + berryObjectMacro(QtViewPart) - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); protected: virtual void CreateQtPartControl(QWidget* parent) = 0; }; } #endif /*BERRYQTVIEWPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp index 0ab95da142..33817094d0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp @@ -1,47 +1,47 @@ /*=================================================================== 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 "berrySameShellProvider.h" namespace berry { -SameShellProvider::SameShellProvider(void* target) : +SameShellProvider::SameShellProvider(QWidget* target) : targetControl(target) { } SameShellProvider::SameShellProvider(Shell::Pointer sh) : targetControl(0), shell(sh) { } Shell::Pointer SameShellProvider::GetShell() const { if (shell != 0) { return shell; } return targetControl == 0 ? Shell::Pointer(0) : Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(targetControl); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h index 39740b2b84..66ad2e8290 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h @@ -1,74 +1,74 @@ /*=================================================================== 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 BERRYSAMESHELLPROVIDER_H_ #define BERRYSAMESHELLPROVIDER_H_ #include #include "berryShell.h" #include #include "berryIShellProvider.h" namespace berry { /** * Standard shell provider that always returns the shell containing the given * control. This will always return the correct shell for the control, even if * the control is reparented. * * @since 3.1 */ class BERRY_UI_QT SameShellProvider : public IShellProvider { private: - void* targetControl; + QWidget* targetControl; Shell::Pointer shell; public: - berryObjectMacro(SameShellProvider); + berryObjectMacro(SameShellProvider) /** * Returns a shell provider that always returns the current * shell for the given control. * * @param targetControl control whose shell will be tracked, or null if getShell() should always * return null */ - SameShellProvider(void* targetControl); + SameShellProvider(QWidget* targetControl); /** * Returns a shell provider that always returns the given shell. * * @param shell the shell which should always be returned, * or null if GetShell() should alway return null */ SameShellProvider(Shell::Pointer shell); /* (non-javadoc) * @see IShellProvider#getShell() */ Shell::Pointer GetShell() const; }; } #endif /* BERRYSAMESHELLPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h index d58edeb19c..293c1a9f0c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h @@ -1,334 +1,328 @@ /*=================================================================== 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" 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 QRect& bounds) = 0; virtual QRect GetBounds() const = 0; virtual void SetLocation(int x, int y) = 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; + 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 dd84deeac3..3a74a5a213 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp @@ -1,580 +1,579 @@ /*=================================================================== 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(); +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 // QRect bounds = shell.getBounds(); // QRect constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} -void* Window::CreateContents(Shell::Pointer parent) +QWidget* 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() +QWidget* Window::GetContents() { return contents; } QPoint Window::GetInitialLocation(const QPoint& initialSize) { - void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); + QWidget* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); QPoint centerPoint(0,0); QRect parentBounds(0,0,0,0); if (parent != 0) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); 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.setX(parentBounds.width()/2); centerPoint.setY(parentBounds.height()/2); } 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()))); } 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; // } QPoint size = this->GetInitialSize(); QPoint location = this->GetInitialLocation(size); shell->SetBounds(this->GetConstrainedShellBounds(QRect(location.x(), location.y(), size.x(), size.y()))); } QRect Window::GetConstrainedShellBounds(const QRect& preferredSize) { QRect result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); QRect bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); if (result.height() > bounds.height()) { result.setHeight(bounds.height()); } if (result.width() > bounds.width()) { result.setWidth(bounds.width()); } 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() +QIcon Window::GetDefaultImage() { - return (defaultImages.size() < 1) ? 0 - : defaultImages[0]; + return (defaultImages.size() < 1) ? QIcon() : defaultImages[0]; } -QList Window::GetDefaultImages() +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) +void Window::SetDefaultImage(const QIcon& image) { - if (image != 0) + if (!image.isNull()) defaultImages.push_back(image); } -void Window::SetDefaultImages(const QList& images) +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 8c6271eced..13b974c5fe 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h @@ -1,731 +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 "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); + 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; + 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; + QWidget* 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 * */ 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); + virtual QWidget* 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(); + virtual QWidget* 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 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 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(); + static QIcon 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(); + 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); + static void SetDefaultImage(const QIcon& 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); + 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/berryWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h index 10b11760e0..9f6bae8aac 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h @@ -1,256 +1,256 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __BERRY_WORKBENCH_PART_H__ #define __BERRY_WORKBENCH_PART_H__ #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPartSite.h" #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Abstract base implementation of all workbench parts. *

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

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

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

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

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

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

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

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

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

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

*/ QString GetContentDescription() const; /* (non-Javadoc) * Method declared on IWorkbenchPart. */ QIcon GetTitleImage() const; /* (non-Javadoc) * Gets the title tool tip text of this part. * * @return the tool tip text */ QString GetTitleToolTip() const; }; } // namespace berry #endif // __BERRY_WORKBENCH_PART_H__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.cpp index 2291f5075f..b6a8445f3e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkControlEvent.cpp @@ -1,42 +1,42 @@ /*=================================================================== 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 "berryGuiTkControlEvent.h" namespace berry { namespace GuiTk { ControlEvent::ControlEvent() : Event() { } -ControlEvent::ControlEvent(void* item, int x, int y, int width, int height) : +ControlEvent::ControlEvent(QWidget* item, int x, int y, int width, int height) : Event() { this->item = item; this->x = x; this->y = y; this->width = width; this->height = height; } } } 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 05157ffc58..4979b40597 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) ControlEvent(); - ControlEvent(void* item, int x = 0, int y = 0, int width = 0, int height = 0); + ControlEvent(QWidget* 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/guitk/berryGuiTkEvent.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkEvent.h index 17d072cfc2..0e12293d55 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkEvent.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkEvent.h @@ -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. ===================================================================*/ #ifndef BERRYGUITKEVENT_H_ #define BERRYGUITKEVENT_H_ #include #include #include namespace berry { namespace GuiTk { /** * Instances of this class are sent as a result of * GUI events. *

* Note: The fields that are filled in depend on the widget. *

* */ class BERRY_UI_QT Event: public Object { public: - berryObjectMacro(Event); + berryObjectMacro(Event) Event(); /** * the widget that issued the event */ - void* item; + QWidget* item; /** * the event specific detail field, as defined by the detail constants * in class Constants */ int detail; /** * depending on the event type, the x offset of the bounding * rectangle of the region that requires painting or the * widget-relative, x coordinate of the pointer at the * time the mouse button was pressed or released */ int x; /** * depending on the event type, the y offset of the bounding * rectangle of the region that requires painting or the * widget-relative, y coordinate of the pointer at the * time the mouse button was pressed or released */ int y; /** * the width of the bounding rectangle of the * region that requires painting */ int width; /** * the height of the bounding rectangle of the * region that requires painting */ int height; /** * the button that was pressed or released; 1 for the * first button, 2 for the second button, and 3 for the * third button, etc. */ int button; /** * depending on the event, the character represented by the key * that was typed. This is the final character that results * after all modifiers have been applied. For example, when the * user types Ctrl+A, the character value is 0x01 (ASCII SOH). * It is important that applications do not attempt to modify the * character value based on a stateMask (such as SWT.CTRL) or the * resulting character will not be correct. */ char character; /** * depending on the event, the key code of the key that was typed, * as defined by the key code constants in class SWT. * When the character field of the event is ambiguous, this field * contains the unaffected value of the original character. For * example, typing Ctrl+M or Enter both result in the character '\r' * but the keyCode field will also contain '\r' when Enter was typed * and 'm' when Ctrl+M was typed. */ int keyCode; /** * depending on the event, the state of the keyboard modifier * keys and mouse masks at the time the event was generated. */ int stateMask; /** * depending on the event, the new text that will be inserted. * Setting this field will change the text that is about to * be inserted or deleted. */ QString text; /** * depending on the event, a flag indicating whether the operation * should be allowed. Setting this field to false will cancel the * operation. */ bool doit; QString ToString() const; }; } } #endif /* BERRYGUITKEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.cpp index 1393c784ef..8416e8d1f3 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.cpp @@ -1,35 +1,35 @@ /*=================================================================== 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 "berryGuiTkSelectionEvent.h" #include namespace berry { namespace GuiTk { -SelectionEvent::SelectionEvent(void* item) : +SelectionEvent::SelectionEvent(QWidget* item) : Event() { this->item = item; } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.h index 3605916ef4..01b26dffd2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkSelectionEvent.h @@ -1,56 +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. ===================================================================*/ #ifndef BERRYGUITKSELECTIONEVENT_H_ #define BERRYGUITKSELECTIONEVENT_H_ #include "berryGuiTkEvent.h" namespace berry { namespace GuiTk { /** * Instances of this class are sent as a result of * widgets being selected. * * @see ISelectionListener */ class BERRY_UI_QT SelectionEvent: public Event { public: berryObjectMacro(SelectionEvent); /** * Constructs a new instance of this class based on the * information in the given untyped event. * * @param item the GUI dependent widget which has been selected */ - SelectionEvent(void* item); + SelectionEvent(QWidget* item); }; } } #endif /* BERRYGUITKSELECTIONEVENT_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 bf970afb08..8c236a418f 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()) { 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 QRect dispBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize(); 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*/, +IDropTarget::Pointer DetachedWindow::Drag(QWidget* /*currentControl*/, 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) { QRect displayBounds = DragUtil::GetDisplayBounds(folder->GetControl()); 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 = 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()); // Save the views. IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_FOLDER); folder->SaveState(childMem); } -void* DetachedWindow::GetControl() +QWidget* DetachedWindow::GetControl() { return folder->GetControl(); } int DetachedWindow::Open() { if (this->GetShell() == 0) { this->Create(); } 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) +QWidget* DetachedWindow::CreateContents(QWidget* 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 51ecbf4e31..11290515ae 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h @@ -1,196 +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 "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; 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 QPoint&, const QRect& ) + * @see org.blueberry.ui.internal.IDragOverListener#Drag(QWidget*, Object::Pointer, const QPoint&, const QRect& ) */ - IDropTarget::Pointer Drag(void* currentControl, + IDropTarget::Pointer Drag(QWidget* currentControl, 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(); + QWidget* 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); + QWidget* CreateContents(QWidget* 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 5b8cb5afa9..edd2b9ddcd 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp @@ -1,361 +1,293 @@ /*=================================================================== 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 "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 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 - 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 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 - QRect snapTarget; - if (target != 0) - { - snapTarget = target->GetSnapRectangle(); - - tracker->SetCursor(target->GetCursor()); - } - else - { - 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) - { - 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 - QRect currentRectangle = tracker->GetRectangle(); - - if (!(currentRectangle == snapTarget)) - { - tracker->SetRectangle(snapTarget); - } - } - -} -DragUtil::TargetListType::Pointer DragUtil::GetTargetList(void* control) +DragUtil::TargetListType::Pointer DragUtil::GetTargetList(QWidget* 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, + QWidget* mostSpecificControl, Object::Pointer draggedObject, 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) +void DragUtil::AddDragTarget(QWidget* 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) +void DragUtil::RemoveDragTarget(QWidget* 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)); } } } } -QRect DragUtil::GetDisplayBounds(void* boundsControl) +QRect DragUtil::GetDisplayBounds(QWidget* boundsControl) { - void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent( + QWidget* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent( boundsControl); if (parent == 0) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(boundsControl); } QRect rect = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds( boundsControl); return Geometry::ToDisplay(parent, rect); } bool DragUtil::PerformDrag(Object::Pointer draggedItem, 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 QRect& sourceBounds, const QPoint& initialLocation, bool allowSnapping) { //final Display display = Display.getCurrent(); // Testing...immediately 'drop' onto the test target if (forcedDropTarget != 0) { QPoint location = forcedDropTarget->GetLocation(); - void* currentControl = + QWidget* 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. QtTracker tracker; //tracker.setStippled(true); - GuiTk::IControlListener::Pointer trackerListener(new TrackerMoveListener( - draggedItem, sourceBounds, initialLocation, allowSnapping)); + QtTrackerMoveListener trackerListener(draggedItem, sourceBounds, + initialLocation, allowSnapping); - tracker.AddControlListener(trackerListener); + trackerListener.connect(&tracker, SIGNAL(Moved(QtTracker*,QPoint)), SLOT(Moved(QtTracker*,QPoint))); // 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 = + QWidget* startControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); if (startControl != 0 && allowSnapping) { target = GetDropTarget(startControl, draggedItem, initialLocation, sourceBounds); } // Set up an initial tracker rectangle QRect startRect = sourceBounds; if (target != 0) { QRect rect = target->GetSnapRectangle(); if (rect.width() != 0 && rect.height() != 0) { startRect = rect; } tracker.SetCursor(target->GetCursor()); } if (startRect.width() != 0 && startRect.height() != 0) { 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(); // // HACK: // // Release the mouse now // if (shell != null) // { // shell.setCapture(false); // } // Done tracking... // Get the current drop target IDropTarget::Pointer dropTarget; QPoint finalLocation = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorLocation(); - void* targetControl = + QWidget* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); dropTarget = GetDropTarget(targetControl, draggedItem, finalLocation, tracker.GetRectangle()); // Cleanup... //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, +IDropTarget::Pointer DragUtil::GetDropTarget(QWidget* toSearch, 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( + for (QWidget* 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); } //QPoint DragUtil::GetEventLoc(GuiTk::ControlEvent::Pointer event) //{ // Control ctrl = (Control) event.widget; // 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 4df7ba7b62..5f80e52cee 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h @@ -1,215 +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. ===================================================================*/ #ifndef BERRYDRAGUTIL_H_ #define BERRYDRAGUTIL_H_ #include #include "guitk/berryGuiTkIControlListener.h" #include "berryTestDropLocation.h" #include "berryIDragOverListener.h" #include "berryIDropTarget.h" #include #include #include namespace berry { /** - * Provides the methods for attaching drag-and-drop listeners to SWT controls. + * Provides the methods for attaching drag-and-drop listeners to 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 QPoint &position, - const QRect& dragRectangle); - - - struct TrackerMoveListener : public GuiTk::IControlListener { - - 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; - QRect sourceBounds; - QPoint initialLocation; - }; + /** + * 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(QWidget* 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, + QWidget* mostSpecificControl, + Object::Pointer draggedObject, + const QPoint &position, + const QRect& dragRectangle); 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 QRect GetDisplayBounds(void* boundsControl); + /** + * 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(QWidget* control, IDragOverListener* target); + + /** + * Removes a drop target from the given control. + * + * @param control + * @param target + */ + static void RemoveDragTarget(QWidget* control, IDragOverListener* target); + + /** + * Shorthand method. Returns the bounding rectangle for the given control, in + * display coordinates. + * + * @param draggedItem + * @param boundsControl + * @return + */ + static QRect GetDisplayBounds(QWidget* boundsControl); static bool PerformDrag(Object::Pointer draggedItem, - const QRect& sourceBounds, const QPoint& 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, // 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 QRect& sourceBounds, const QPoint& initialLocation, - bool allowSnapping); + 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 QPoint& position, const QRect& dragRectangle); + static IDropTarget::Pointer GetDropTarget(QWidget* toSearch, + Object::Pointer draggedObject, + const QPoint& position, + const QRect& dragRectangle); /** * Returns the location of the given event, in display coordinates * @return */ //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 9ff0db04d8..e3e4eeb709 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) +QWidget* EditorSashContainer::CreateParent(QWidget* 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) + WorkbenchPage* page, QWidget* 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; 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(); 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(); + QWidget* 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) +void EditorSashContainer::CreateControl(QWidget* 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/berryEditorSashContainer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.h index dc2a0c5ca3..ef30614c61 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.h @@ -1,253 +1,253 @@ /*=================================================================== 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 BERRYEDITORSASHCONTAINER_H_ #define BERRYEDITORSASHCONTAINER_H_ #include "berryPartSashContainer.h" #include "berryPartStack.h" #include namespace berry { /** * Represents the area set aside for editor workbooks. * This container only accepts editor stacks (PartStack) and PartSash * as layout parts. * * Note no views are allowed within this container. */ class EditorSashContainer: public PartSashContainer { public: berryObjectMacro(EditorSashContainer) private: QList editorWorkbooks; PartStack::Pointer activeEditorWorkbook; // DropTarget dropTarget; void AddDropSupport(); PartStack::Pointer NewEditorWorkbook(); protected: /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#addChild(org.blueberry.ui.internal.PartSashContainer.RelationshipInfo) */ void AddChild(const RelationshipInfo& info); /** * Notification that a child layout part has been * added to the container. Subclasses may override * this method to perform any container specific * work. */ 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. */ void ChildRemoved(LayoutPart::Pointer child); PartStack::Pointer CreateDefaultWorkbook(); /** * Subclasses override this method to specify * the composite to use to parent all children * layout parts it contains. */ - void* CreateParent(void* parentWidget); + QWidget* CreateParent(QWidget* parentWidget); /** * Subclasses override this method to dispose * of any swt resources created during createParent. */ void DisposeParent(); /** * Return true is the workbook specified * is the active one. */ bool IsActiveWorkbook(PartStack::Pointer workbook); //TODO DND // /* package */DropTarget getDropTarget() { // return dropTarget; // } /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#createStack(org.blueberry.ui.internal.LayoutPart) */ PartStack::Pointer CreateStack(); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#setVisiblePart(org.blueberry.ui.internal.ILayoutContainer, org.blueberry.ui.internal.LayoutPart) */ void SetVisiblePart(ILayoutContainer::Pointer container, PartPane::Pointer visiblePart); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#getVisiblePart(org.blueberry.ui.internal.ILayoutContainer) */ LayoutPart::Pointer GetVisiblePart(ILayoutContainer::Pointer container); public: static const QString DEFAULT_WORKBOOK_ID; EditorSashContainer(const QString& editorId, WorkbenchPage* page, - void* parent); + QWidget* parent); bool AllowsAdd(LayoutPart::Pointer layoutPart); /** * Add an editor to the active workbook. */ void AddEditor(PartPane::Pointer pane, PartStack::Pointer stack); /** * Hides the min/max buttons for all editor stacks * -except- for the upper/left one. */ void UpdateStackButtons(); /** * @param stacks * @return the EditorStack in the upper right position */ PartStack::Pointer GetUpperRightEditorStack(); /** * @param stacks * @return the EditorStack in the upper right position */ PartStack::Pointer GetUpperRightEditorStack( const ILayoutContainer::ChildrenType& stacks); /** * Return the editor workbook which is active. */ PartStack::Pointer GetActiveWorkbook(); /** * Return the editor workbook id which is active. */ QString GetActiveWorkbookID(); /** * Return the all the editor workbooks. */ QList GetEditorWorkbooks(); /** * Return the all the editor workbooks. */ std::size_t GetEditorWorkbookCount(); /** * Find the sashes around the specified part. */ void FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes); /** * Remove all the editors */ void RemoveAllEditors(); /** * Remove an editor from its' workbook. */ void RemoveEditor(PartPane::Pointer pane); /** * @see IPersistablePart */ bool RestoreState(IMemento::Pointer memento); /** * @see IPersistablePart */ bool SaveState(IMemento::Pointer memento); /** * Set the editor workbook which is active. */ void SetActiveWorkbook(PartStack::Pointer newWorkbook, bool hasFocus); /** * Set the editor workbook which is active. */ void SetActiveWorkbookFromID(const QString& id); PartStack::Pointer GetWorkbookFromID(const QString& id); /** * Updates the editor area's tab list to include the active * editor and its tab. */ void UpdateTabList(); /** * @see org.blueberry.ui.internal.LayoutPart#createControl(org.blueberry.swt.widgets.Composite) */ - void CreateControl(void* parent); + void CreateControl(QWidget* parent); /** * @see org.blueberry.ui.internal.LayoutPart#getImportance() */ bool IsCompressible(); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#isStackType(org.blueberry.ui.internal.LayoutPart) */ bool IsStackType(ILayoutContainer::Pointer toTest); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#isPaneType(org.blueberry.ui.internal.LayoutPart) */ bool IsPaneType(LayoutPart::Pointer toTest); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#pickPartToZoom() */ // LayoutPart pickPartToZoom() { // return getActiveWorkbook(); // } /** * Restore the presentation state. Loop over the workbooks, create the appropriate serializer and pass to the presentation. * * @param areaMem the memento containing presentation * @return the restoration status */ bool RestorePresentationState(IMemento::Pointer areaMem); }; } #endif /* BERRYEDITORSASHCONTAINER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.cpp index 5e557cdbd2..75cf082157 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.cpp @@ -1,50 +1,50 @@ /*=================================================================== 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 "berryErrorViewPart.h" namespace berry { ErrorViewPart::ErrorViewPart() { } ErrorViewPart::ErrorViewPart(const QString& title, const QString& error) : title(title), error(error) { } -void ErrorViewPart::CreatePartControl(void* parent) +void ErrorViewPart::CreatePartControl(QWidget* parent) { if (!error.isEmpty()) { statusPart = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateStatusPart( parent, title, error); } } void ErrorViewPart::SetPartName(const QString& newName) { ViewPart::SetPartName(newName); } void ErrorViewPart::SetFocus() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.h index a9b5aa5660..65cce6f8c2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryErrorViewPart.h @@ -1,82 +1,80 @@ /*=================================================================== 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 BERRYERRORVIEWPART_H_ #define BERRYERRORVIEWPART_H_ #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryViewPart.h" namespace berry { /** * This part is shown instead the views with errors. - * - * @since 3.3 */ class ErrorViewPart : public ViewPart { public: - berryObjectMacro(ErrorViewPart); + berryObjectMacro(ErrorViewPart) /** * Creates instance of the class */ ErrorViewPart(); /** * Creates instance of the class * * @param error the status */ ErrorViewPart(const QString& title, const QString& error); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); /* * (non-Javadoc) * * @see org.eclipse.ui.part.ViewPart#setPartName(java.lang.String) */ void SetPartName(const QString& newName); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ void SetFocus(); private: //IStatus error; QString title; QString error; Object::Pointer statusPart; }; } #endif /* BERRYERRORVIEWPART_H_ */ 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 9e5ddeea3e..b538d9a5a9 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h @@ -1,65 +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 "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, + virtual IDropTarget::Pointer Drag(QWidget* currentControl, const Object::Pointer& draggedObject, const QPoint& position, const QRect& dragRectangle) = 0; }; } #endif /* BERRYIDRAGOVERLISTENER_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 cfbb0c9b37..871130f09b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp @@ -1,345 +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() { } QRect LayoutPart::GetBounds() { if (this->GetControl() == 0) 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; } QSize LayoutPart::GetSize() { 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 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(); + QWidget* 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::MoveAbove(QWidget* /*refControl*/) { } -void LayoutPart::Reparent(void* newParent) +void LayoutPart::Reparent(QWidget* newParent) { - void* control = this->GetControl(); + QWidget* 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(); + QWidget* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl); } return false; } bool LayoutPart::IsVisible() { - void* ctrl = this->GetControl(); + QWidget* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsVisible(ctrl); } return false; } void LayoutPart::SetVisible(bool makeVisible) { - void* ctrl = this->GetControl(); + QWidget* 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*/) +bool LayoutPart::IsFocusAncestor(QWidget* /*ctrl*/) { // Control f = ctrl.getDisplay().getFocusControl(); // while (f != null && f != ctrl) // { // f = f.getParent(); // } // return f == ctrl; return false; } void LayoutPart::SetBounds(const QRect& r) { - void* ctrl = this->GetControl(); + QWidget* 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 86d5c4eb0f..a75cd331c1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h @@ -1,303 +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 "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; + public: virtual void CreateControl(QWidget* 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: 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 QWidget* 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 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 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); + public: virtual void MoveAbove(QWidget* refControl); /** * Reparent a part. */ - public: virtual void Reparent(void* newParent); + public: virtual void Reparent(QWidget* 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); + private: virtual bool IsFocusAncestor(QWidget* ctrl); /** * Sets the presentation bounds. */ 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 82c3ecf95e..8a489fdcfe 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)); 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 = 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(); LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width(), nodeBounds.height(), left, right, nodeBounds.width()); eventRect.setX(nodeBounds.x() + sizes.left); // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { eventRect = QRect(eventRect.y(), eventRect.x(), eventRect.height(), eventRect.width()); } event->x = eventRect.x(); event->y = eventRect.y(); } -void LayoutPartSash::CreateControl(void* /*parent*/) +void LayoutPartSash::CreateControl(QWidget* /*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 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; } QRect LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } -void* LayoutPartSash::GetControl() +QWidget* 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)); QRect nodeBounds = node->GetBounds(); //Recompute ratio x -= nodeBounds.x(); y -= nodeBounds.y(); if (style == Constants::VERTICAL) { this->SetSizes(x, nodeBounds.width() - x - this->GetSashSize()); } else { 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 ef5d5dadfc..a5af887b8e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h @@ -1,184 +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; + QWidget* sash; bool enabled; PartSashContainer* rootContainer; int style; LayoutPartSash::Pointer preLimit; LayoutPartSash::Pointer postLimit; int left; int right; 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); + void CreateControl(QWidget* parent); /** * Creates the underlying SWT control. * * @since 3.1 */ private: void DoCreateControl(); public: 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: QRect GetBounds(); /** * Returns the part control. */ public: - void* GetControl(); + QWidget* 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 fdab418d8c..dcafd29c70 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.cpp @@ -1,481 +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 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); } 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 QRect& bounds) { if (!(bounds == currentBounds) || forceLayout) { currentBounds = bounds; this->DoSetBounds(currentBounds); forceLayout = false; } } 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::CreateControl(QWidget* /*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 9cb62bd853..39e7a12475 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTree.h @@ -1,370 +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 "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; 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 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. */ 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 QRect& bounds); protected: /** * Resize the parts on this tree to fit in 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); + virtual void CreateControl(QWidget* 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 2193b84808..accd9fdb60 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp @@ -1,723 +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 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(); QRect bounds = sash->GetBounds(); if (sash->IsVertical()) { 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)) { 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(); + QWidget* 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 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; } 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 = FlipRect(bounds); } 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); 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 = 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) +void LayoutTreeNode::CreateControl(QWidget* 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) { +//void LayoutTreeNode::UpdateSashes(QWidget* 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 65baa5a47b..0fe032466c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h @@ -1,229 +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 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 QRect& bounds); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutTree#createControl(org.blueberry.swt.widgets.Composite) */ - public: void CreateControl(void* parent); + public: void CreateControl(QWidget* 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); + //public: void UpdateSashes(QWidget* 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 d7bab9d5ed..e7d3b87920 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) { +void PartPane::CreateControl(QWidget* 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); } } QRect PartPane::GetParentBounds() { - void* ctrl = this->GetControl(); + QWidget* 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() +QWidget* 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) +void PartPane::MoveAbove(QWidget* 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(); + QWidget* containerControl = container == 0 ? 0 : container.Cast()->GetControl(); if (containerControl != 0) { - void* control = this->GetControl(); - void* newParent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(containerControl); + QWidget* control = this->GetControl(); + QWidget* 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 PartPane::Reparent(QWidget* newParent) { - void* control = this->GetControl(); + QWidget* 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() +QToolBar* 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 181bb7cf83..c779d471c8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h @@ -1,436 +1,438 @@ /*=================================================================== 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 "berryIPropertyChangeListener.h" #include "guitk/berryGuiTkIControlListener.h" +class QToolBar; + 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; + protected: QWidget* 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; + /*Sash*/ QWidget* left; + /*Sash*/ QWidget* right; + /*Sash*/ QWidget* top; + /*Sash*/ QWidget* 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*) + * IWorkbenchPart::CreatePartControl(QWidget*) */ - public: virtual void CreateControl(void* parent); + public: virtual void CreateControl(QWidget* 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: QRect GetParentBounds(); /** * Get the control. */ - public: void* GetControl(); + public: QWidget* 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); + public: void MoveAbove(QWidget* 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); + public: void Reparent(QWidget* 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(); + public: virtual QToolBar* 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/berryPartPlaceholder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.cpp index 82668fdd3c..eb44cba2ee 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.cpp @@ -1,52 +1,52 @@ /*=================================================================== 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 "berryPartPlaceholder.h" #include "berryPartStack.h" namespace berry { const QString PartPlaceholder::WILD_CARD = "*"; PartPlaceholder::PartPlaceholder(const QString& id) : LayoutPart(id) { } -void PartPlaceholder::CreateControl(void* /*parent*/) +void PartPlaceholder::CreateControl(QWidget* /*parent*/) { // do nothing } -void* PartPlaceholder::GetControl() +QWidget* PartPlaceholder::GetControl() { return 0; } bool PartPlaceholder::HasWildCard() { return this->GetID().indexOf(WILD_CARD) != -1; } bool PartPlaceholder::IsPlaceHolder() const { return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.h index 547986f048..89f24865f7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPlaceholder.h @@ -1,66 +1,66 @@ /*=================================================================== 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 BERRYPARTPLACEHOLDER_H_ #define BERRYPARTPLACEHOLDER_H_ #include "berryLayoutPart.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * A PlaceHolder is a non-visible stand-in for a layout part. */ class PartPlaceholder : public LayoutPart { public: berryObjectMacro(PartPlaceholder) /** * Placeholder ids may contain wildcards. This is the wildcard string. * * @since 3.0 */ static const QString WILD_CARD; // = "*"; PartPlaceholder(const QString& id); /** * Creates the SWT control */ - void CreateControl(void* parent); + void CreateControl(QWidget* parent); /** * Get the part control. This method may return null. */ - void* GetControl(); + QWidget* GetControl(); /** * Returns whether this placeholder has a wildcard. * * @since 3.0 */ bool HasWildCard(); bool IsPlaceHolder() const; }; } #endif /*BERRYPARTPLACEHOLDER_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 128666fdda..e32ee3fa74 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp @@ -1,1274 +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(); } } CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { return QtDragManager::PositionToCursorType(cursor); } QRect PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { 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) : + WorkbenchPage* _page, QWidget* _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); } QRect bounds; if (this->GetParent() == 0) { - void* control = this->GetPage()->GetClientComposite(); + QWidget* control = this->GetPage()->GetClientComposite(); if (control != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { bounds = QRect(0, 0, 800, 600); } 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 QRect& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { return Geometry::GetDimension(outerBounds, horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == 0) { 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) +void PartSashContainer::CreateControl(QWidget* 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(); } QRect PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() const { return children; } -void* PartSashContainer::GetControl() +QWidget* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } -void* PartSashContainer::GetParent() +QWidget* 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 QRect& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } -IDropTarget::Pointer PartSashContainer::Drag(void* /*currentControl*/, +IDropTarget::Pointer PartSashContainer::Drag(QWidget* /*currentControl*/, 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); } 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 (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { - void* targetControl = targetPart->GetControl(); + QWidget* targetControl = targetPart->GetControl(); 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 87c9eefc04..de547c0273 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h @@ -1,699 +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 "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; + QWidget* 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; + QWidget* 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(); CursorType GetCursor(); 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); + QWidget* 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 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); + void CreateControl(QWidget* 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; + virtual QWidget* CreateParent(QWidget* 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: QRect GetBounds(); /** * @see ILayoutContainer#getChildren */ public: ChildrenType GetChildren() const; /** * @see LayoutPart#getControl */ public: - void* GetControl(); + QWidget* 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(); + virtual QWidget* 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 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.QPoint, org.blueberry.swt.graphics.QRect) */ public: - IDropTarget::Pointer Drag(void* currentControl, const Object::Pointer& draggedObject, + IDropTarget::Pointer Drag(QWidget* currentControl, const Object::Pointer& draggedObject, 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 1d1c1e5680..2855f211b0 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); } } CursorType PartStack::PartStackDropResult::GetCursor() { return CURSOR_CENTER; } 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, QPoint& initialLocation, bool keyboard) { partStack->DragStart(beingDragged, initialLocation, keyboard); } 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 = + QWidget* 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) +void PartStack::CreateControl(QWidget* 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 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 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) +void PartStack::CreateControl(QWidget* /*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(); + //QWidget* 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); } } QRect PartStack::GetBounds() { if (this->GetPresentation() == 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() +QWidget* 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() +QWidget* 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 PartStack::Reparent(QWidget* newParent) { - void* control = this->GetControl(); + QWidget* 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(); + QWidget* 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) +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(); + return QList(); } 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, 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 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()); // 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.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 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()); // 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.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 f23b8663ed..37ffd8542d 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, QPoint& 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(); CursorType GetCursor(); 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); + public: void CreateControl(QWidget* parent); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getDropTarget(java.lang.Object, org.blueberry.swt.graphics.QPoint) */ 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: QRect GetBounds(); /** * See IVisualContainer#getChildren */ public: ChildVector GetChildren() const; - public: void* GetControl(); + public: QWidget* 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(); + public: QWidget* 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); + public: void Reparent(QWidget* 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); + public: void CreateControl(QWidget* parent, StackPresentation::Pointer presentation); /** * Sets the presentation bounds. */ 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); + public: QList GetTabList(LayoutPart::Pointer part); /** * * @param beingDragged * @param initialLocation * @param keyboard */ private: void DragStart(IPresentablePart::Pointer beingDragged, QPoint& initialLocation, bool keyboard); 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 65694e00d9..5343cb83ee 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp @@ -1,1813 +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() +QWidget* 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) { 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) { 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()); } // // 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/berryPerspective.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h index 422863a217..49d1c9a6de 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h @@ -1,636 +1,636 @@ /*=================================================================== 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 BERRYPERSPECTIVE_H_ #define BERRYPERSPECTIVE_H_ #include #include "berryPerspectiveDescriptor.h" #include "berryPartPlaceholder.h" #include "berryViewLayoutRec.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryPageLayout.h" #include "berryPartPane.h" #include "berryIWorkbenchPartReference.h" #include "berryIViewReference.h" #include "berryIViewPart.h" namespace berry { class ViewFactory; class PerspectiveHelper; /** * \ingroup org_blueberry_ui_internal * */ class Perspective : public Object { public: berryObjectMacro(Perspective) friend class WorkbenchPage; bool ContainsView(const QString& viewId) const; private: ViewFactory* viewFactory; QHash mapIDtoViewLayoutRec; static const QString VERSION_STRING; // = "0.016"; /** * Reference to the part that was previously active * when this perspective was deactivated. */ IWorkbenchPartReference::Pointer oldPartRef; protected: PerspectiveDescriptor::Pointer descriptor; WorkbenchPage* page; // Editor Area management LayoutPart::Pointer editorArea; PartPlaceholder::Pointer editorHolder; bool editorHidden; int editorAreaState; //ArrayList alwaysOnActionSets; //ArrayList alwaysOffActionSets; QList showViewShortcuts; QList perspectiveShortcuts; bool fixed; QList showInPartIds; //HashMap showInTimes; IMemento::Pointer memento; PerspectiveHelper* presentation; bool shouldHideEditorsOnActivate; PageLayout::Pointer layout; /** * ViewManager constructor comment. */ public: Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page); /** * ViewManager constructor comment. */ protected: Perspective(WorkbenchPage::Pointer page); protected: void Init(WorkbenchPage::Pointer page); /** * Moves a part forward in the Z order of a perspective so it is visible. * * @param part the part to bring to move forward * @return true if the part was brought to top, false if not. */ public: bool BringToTop(IViewReference::Pointer ref); /** * Returns whether a view exists within the perspective. */ public: bool ContainsView(IViewPart::Pointer view); /** * Create the initial list of action sets. */ // protected: void CreateInitialActionSets(List outputList, List stringList) { // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // Iterator iter = stringList.iterator(); // while (iter.hasNext()) { // String id = (String) iter.next(); // IActionSetDescriptor desc = reg.findActionSet(id); // if (desc != null) { // outputList.add(desc); // } else { // WorkbenchPlugin.log("Unable to find Action Set: " + id);//$NON-NLS-1$ // } // } // } /** * Create a presentation for a perspective. */ private: void CreatePresentation(PerspectiveDescriptor::Pointer persp); /** * Dispose the perspective and all views contained within. */ public: ~Perspective(); private: void DisposeViewRefs(); /** * Finds the view with the given ID that is open in this page, or null * if not found. * * @param viewId the view ID */ public: IViewReference::Pointer FindView(const QString& viewId); /** * Finds the view with the given id and secondary id that is open in this page, * or null if not found. * * @param viewId the view ID * @param secondaryId the secondary ID */ public: IViewReference::Pointer FindView(const QString& id, const QString& secondaryId); /** * Returns the window's client composite widget * which views and editor area will be parented. */ - public: void* GetClientComposite(); + public: QWidget* GetClientComposite(); /** * Returns the perspective. */ public: IPerspectiveDescriptor::Pointer GetDesc(); /** * Returns the pane for a view reference. */ protected: PartPane::Pointer GetPane(IViewReference::Pointer ref); /** * Returns the perspective shortcuts associated with this perspective. * * @return an array of perspective identifiers */ public: QList GetPerspectiveShortcuts(); /** * Returns the presentation. */ public: PerspectiveHelper* GetPresentation() const; /** * Returns the show view shortcuts associated with this perspective. * * @return an array of view identifiers */ public: QList GetShowViewShortcuts(); /** * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: QList GetViewReferences(); /** * Hide the editor area if visible */ protected: void HideEditorArea(); /** * Hide the editor area if visible */ protected: void HideEditorAreaLocal(); public: bool HideView(IViewReference::Pointer ref); /* * Return whether the editor area is visible or not. */ protected: bool IsEditorAreaVisible(); /** * Returns the view layout rec for the given view reference, * or null if not found. If create is true, it creates the record * if not already created. */ public: ViewLayoutRec::Pointer GetViewLayoutRec(IViewReference::Pointer ref, bool create); /** * Returns the view layout record for the given view id * or null if not found. If create is true, it creates the record * if not already created. */ private: ViewLayoutRec::Pointer GetViewLayoutRec(const QString& viewId, bool create); /** * Returns true if a layout or perspective is fixed. */ public: bool IsFixedLayout(); /** * Returns true if a view is standalone. * * @since 3.0 */ public: bool IsStandaloneView(IViewReference::Pointer ref); /** * Returns whether the title for a view should * be shown. This applies only to standalone views. * * @since 3.0 */ public: bool GetShowTitleView(IViewReference::Pointer ref); /** * Creates a new presentation from a persistence file. * Note: This method should not modify the current state of the perspective. */ private: void LoadCustomPersp(PerspectiveDescriptor::Pointer persp); private: void UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status); /** * Create a presentation for a perspective. * Note: This method should not modify the current state of the perspective. */ protected: void LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp); // private: void RemoveAlwaysOn(IActionSetDescriptor::Pointer descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOnActionSets.contains(descriptor)) { // return; // } // // alwaysOnActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); // } // } // protected: void AddAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_MASK); // } // removeAlwaysOn(descriptor); // } // protected: void AddAlwaysOn(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOnActionSets.contains(descriptor)) { // return; // } // alwaysOnActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_SHOW); // } // removeAlwaysOff(descriptor); // } // private: void RemoveAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK); // } // } /** * activate. */ protected: void OnActivate(); private: /** * An 'orphan' perspective is one that was originally created through a * contribution but whose contributing bundle is no longer available. In * order to allow it to behave correctly within the environment (for Close, * Reset...) we turn it into a 'custom' perspective on its first activation. */ void FixOrphan(); /** * deactivate. */ protected: void OnDeactivate(); /** * Notifies that a part has been activated. */ public: void PartActivated(IWorkbenchPart::Pointer activePart); /** * The user successfully performed a Show In... action on the specified part. * Update the history. */ public: void PerformedShowIn(const QString& partId); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(IMemento::Pointer memento); bool CreateReferences(const QList& views); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(); /** * Returns the ActionSets read from perspectiveExtensions in the registry. */ // protected: ArrayList GetPerspectiveExtensionActionSets() { // PerspectiveExtensionReader reader = new PerspectiveExtensionReader(); // reader // .setIncludeOnlyTags(new String[] { IWorkbenchRegistryConstants.TAG_ACTION_SET }); // PageLayout layout = new PageLayout(); // reader.extendLayout(null, descriptor.getOriginalId(), layout); // return layout.getActionSets(); // } /** * Returns the Show In... part ids read from the registry. */ protected: QList GetShowInIdsFromRegistry(); /** * Save the layout. */ public: void SaveDesc(); /** * Save the layout. */ public: void SaveDescAs(IPerspectiveDescriptor::Pointer desc); /** * Save the layout. */ public: bool SaveState(IMemento::Pointer memento); /** * Save the layout. */ private: bool SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState); // public: void turnOnActionSets(IActionSetDescriptor[] newArray) { // for (int i = 0; i < newArray.length; i++) { // IActionSetDescriptor descriptor = newArray[i]; // // addAlwaysOn(descriptor); // } // } // public: void turnOffActionSets(IActionSetDescriptor[] toDisable) { // for (int i = 0; i < toDisable.length; i++) { // IActionSetDescriptor descriptor = toDisable[i]; // // turnOffActionSet(descriptor); // } // } // public: void turnOffActionSet(IActionSetDescriptor toDisable) { // addAlwaysOff(toDisable); // } /** * Sets the perspective actions for this page. * This is List of Strings. */ public: void SetPerspectiveActionIds(const QList& list); /** * Sets the ids of the parts to list in the Show In... prompter. * This is a List of Strings. */ public: void SetShowInPartIds(const QList& list); /** * Sets the ids of the views to list in the Show View shortcuts. * This is a List of Strings. */ public: void SetShowViewActionIds(const QList& list); /** * Show the editor area if not visible */ protected: void ShowEditorArea(); /** * Show the editor area if not visible */ protected: void ShowEditorAreaLocal(); public: void SetEditorAreaState(int newState); public: int GetEditorAreaState(); /** * */ public: void RefreshEditorAreaVisibility(); /** * Resolves a view's id into its reference, creating the * view if necessary. * * @param viewId The primary id of the view (must not be * null * @param secondaryId The secondary id of a multiple-instance view * (may be null). * * @return The reference to the specified view. This may be null if the * view fails to create (i.e. thrown a PartInitException) */ public: IViewReference::Pointer GetViewReference(const QString& viewId, const QString& secondaryId); /** * Shows the view with the given id and secondary id. */ public: IViewPart::Pointer ShowView(const QString& viewId, const QString& secondaryId); /** * Returns the old part reference. * Returns null if there was no previously active part. * * @return the old part reference or null */ public: IWorkbenchPartReference::Pointer GetOldPartRef(); /** * Sets the old part reference. * * @param oldPartRef The old part reference to set, or null */ public: void SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef); // //for dynamic UI // protected: void AddActionSet(IActionSetDescriptor newDesc) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(newDesc.getId())) { // removeAlwaysOn(desc); // removeAlwaysOff(desc); // break; // } // } // addAlwaysOn(newDesc); // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // // for dynamic UI // /* package */void removeActionSet(String id) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOn(desc); // break; // } // } // // for (int i = 0; i < alwaysOffActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOffActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOff(desc); // break; // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // void removeActionSet(IActionSetDescriptor toRemove) { // removeAlwaysOn(toRemove); // removeAlwaysOff(toRemove); // } /** * Returns whether the given view is closeable in this perspective. * * @since 3.0 */ public: bool IsCloseable(IViewReference::Pointer reference); /** * Returns whether the given view is moveable in this perspective. * * @since 3.0 */ public: bool IsMoveable(IViewReference::Pointer reference); /** * 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; /** * Sanity-checks the LayoutParts in this perspective. Throws an Assertation exception * if an object's internal state is invalid. */ public: void TestInvariants(); // public: IActionSetDescriptor[] getAlwaysOnActionSets() { // return (IActionSetDescriptor[]) alwaysOnActionSets.toArray(new IActionSetDescriptor[alwaysOnActionSets.size()]); // } // public: IActionSetDescriptor[] getAlwaysOffActionSets() { // return (IActionSetDescriptor[]) alwaysOffActionSets.toArray(new IActionSetDescriptor[alwaysOffActionSets.size()]); // } /** * Used to restrict the use of the new min/max behavior to envoronments * in which it has a chance of working... * * @param activePerspective We pass this in as an arg so others won't have * to check it for 'null' (which is one of the failure cases) * */ public: static bool UseNewMinMax(Perspective::Pointer activePerspective); }; } #endif /*BERRYPERSPECTIVE_H_*/ 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 e2e24142b2..2828e3a19a 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 QPoint& /*position*/, + QWidget* /*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 QRect& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, const QRect& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, 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()); return; } } } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach 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()); return; } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->Detach(stack, dragRectangle.x(), dragRectangle.y()); } } CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { 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(); + QWidget* 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) +void PerspectiveHelper::Activate(QWidget* 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(); + QWidget* 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. 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.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. 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.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); QRect bounds = pane->GetParentBounds(); this->DetachPart(pane, bounds.x(), bounds.y()); } } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part) { // Calculate detached window size. 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 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->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(); + QWidget* 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("", 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(); } 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 20996a421c..e40519c66a 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; + QWidget* 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; 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, + IDropTarget::Pointer Drag(QWidget* currentControl, 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 QRect& dragRectangle); /** * @param part * @param dragRectangle * @since 3.1 */ void SetTarget(PartStack::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer part, const QRect& dragRectangle); void Drop(); CursorType GetCursor(); private: PartPane::Pointer part; PartStack::Pointer stack; 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); + void Activate(QWidget* 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 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 -> 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: 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 388643890a..959e4aae72 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*/) +PresentablePart::PresentablePart(PartPane::Pointer part, QWidget* /*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 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() +QToolBar* PresentablePart::GetToolBar() { if (enableOutputs) { return this->GetPane()->GetToolBar(); } return 0; } bool PresentablePart::IsCloseable() const { return part->IsCloseable(); } -void* PresentablePart::GetControl() +QWidget* 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 2ae7df9400..3277066599 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; 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); + PresentablePart(SmartPointer part, QWidget* 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.QRect) */ 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(); + QToolBar* 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(); + QWidget* 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/berryPresentationFactoryUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.cpp index 30408d8571..bd747575c9 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.cpp @@ -1,69 +1,69 @@ /*=================================================================== 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 "berryPresentationFactoryUtil.h" namespace berry { const int PresentationFactoryUtil::ROLE_EDITOR = 0x01; const int PresentationFactoryUtil::ROLE_VIEW = 0x02; const int PresentationFactoryUtil::ROLE_STANDALONE = 0x03; const int PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE = 0x04; StackPresentation::Pointer PresentationFactoryUtil::CreatePresentation( - IPresentationFactory* factory, int role, void* parent, + IPresentationFactory* factory, int role, QWidget* parent, IStackPresentationSite::Pointer site, IPresentationSerializer* serializer, IMemento::Pointer memento) { StackPresentation::Pointer presentation; switch (role) { case ROLE_EDITOR: presentation = factory->CreateEditorPresentation(parent, site); break; case ROLE_STANDALONE: presentation = factory->CreateStandaloneViewPresentation(parent, site, true); break; case ROLE_STANDALONE_NOTITLE: presentation = factory->CreateStandaloneViewPresentation(parent, site, false); break; default: presentation = factory->CreateViewPresentation(parent, site); } //don't initialize editors at creation time - it will not contain any parts if (role != ROLE_EDITOR && memento != 0 && serializer != 0) { presentation->RestoreState(serializer, memento); } return presentation; } PresentationFactoryUtil::PresentationFactoryUtil() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.h index 0fcaff0466..b4f968328d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPresentationFactoryUtil.h @@ -1,53 +1,53 @@ /*=================================================================== 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 BERRYPRESENTATIONFACTORYUTIL_H_ #define BERRYPRESENTATIONFACTORYUTIL_H_ #include "presentations/berryIPresentationFactory.h" #include "presentations/berryIStackPresentationSite.h" #include "presentations/berryIPresentationSerializer.h" namespace berry { class PresentationFactoryUtil { public: static const int ROLE_EDITOR; // = 0x01; static const int ROLE_VIEW; // = 0x02; static const int ROLE_STANDALONE; // = 0x03; static const int ROLE_STANDALONE_NOTITLE; // = 0x04; static StackPresentation::Pointer CreatePresentation( - IPresentationFactory* factory, int role, void* parent, + IPresentationFactory* factory, int role, QWidget* parent, IStackPresentationSite::Pointer site, IPresentationSerializer* serializer, IMemento::Pointer memento); private: PresentationFactoryUtil(); }; } #endif /* BERRYPRESENTATIONFACTORYUTIL_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 86e407a37e..dd230297b3 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp @@ -1,203 +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 QRect& bounds) { widget->setGeometry(bounds); } QRect QtShell::GetBounds() const { return widget->frameGeometry(); } void QtShell::SetLocation(int x, int y) { widget->move(x, y); } QPoint QtShell::ComputeSize(int /*wHint*/, int /*hHint*/, bool changed) { if (changed) widget->updateGeometry(); QSize size(widget->size()); 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*/) +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 5b930568fb..e1bae87184 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h @@ -1,85 +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 namespace berry { class QtAbstractControlWidget; class QtShell : public Shell { public: QtShell(QWidget* parent = 0, Qt::WindowFlags flags = 0); ~QtShell(); // berry::Shell void SetBounds(const QRect& bounds); QRect GetBounds() const; void SetLocation(int x, int y); 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); + 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 b268f5dba2..f851e2378d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp @@ -1,287 +1,332 @@ /*=================================================================== 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 "berryTweaklets.h" + #include "berryQtTracker.h" #include "berryConstants.h" +#include "berryIDropTarget.h" +#include "berryDragUtil.h" +#include "berryGuiWidgetsTweaklet.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); + emit tracker->Moved(tracker, 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(CURSOR_TOP, cursorTop); QPixmap pixCursorRight(":/org.blueberry.ui.qt/cursor_right.xpm"); QCursor* cursorRight = new QCursor(pixCursorRight, 23, 15); cursorMap.insert(CURSOR_RIGHT, cursorRight); QPixmap pixCursorBottom(":/org.blueberry.ui.qt/cursor_bottom.xpm"); QCursor* cursorBottom = new QCursor(pixCursorBottom, 16, 23); cursorMap.insert(CURSOR_BOTTOM, cursorBottom); QPixmap pixCursorLeft(":/org.blueberry.ui.qt/cursor_left.xpm"); QCursor* cursorLeft = new QCursor(pixCursorLeft, 8, 15); cursorMap.insert(CURSOR_LEFT, cursorLeft); QPixmap pixCursorCenter(":/org.blueberry.ui.qt/cursor_center.xpm"); QCursor* cursorCenter = new QCursor(pixCursorCenter, 15, 15); cursorMap.insert(CURSOR_CENTER, cursorCenter); QPixmap pixCursorOffscreen(":/org.blueberry.ui.qt/cursor_offscreen.xpm"); QCursor* cursorOffscreen = new QCursor(pixCursorOffscreen, 15, 15); cursorMap.insert(CURSOR_OFFSCREEN, cursorOffscreen); QCursor* cursorInvalid = new QCursor(Qt::ForbiddenCursor); cursorMap.insert(CURSOR_INVALID, cursorInvalid); } QtTracker::~QtTracker() { delete rubberBand; for (QHash::iterator iter = cursorMap.begin(); iter != cursorMap.end(); ++iter) { delete iter.value(); } } QRect QtTracker::GetRectangle() const { return rubberBand->geometry(); } void QtTracker::SetRectangle(const QRect& rectangle) { rubberBand->setGeometry(rectangle); } 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) +QtTrackerMoveListener::QtTrackerMoveListener(Object::Pointer draggedItem, + const QRect& sourceBounds, + const QPoint& initialLocation, + bool allowSnapping) + : allowSnapping(allowSnapping) + , draggedItem(draggedItem) + , sourceBounds(sourceBounds) + , initialLocation(initialLocation) { - controlEvents.AddListener(listener); } -void QtTracker::RemoveControlListener(GuiTk::IControlListener::Pointer listener) +void QtTrackerMoveListener::Moved(QtTracker* tracker, const QPoint& location) { - controlEvents.RemoveListener(listener); -} + // Select a drop target; use the global one by default + IDropTarget::Pointer target; -void QtTracker::HandleMove(const QPoint& globalPoint) -{ - GuiTk::ControlEvent::Pointer event( - new GuiTk::ControlEvent(this, globalPoint.x(), globalPoint.y(), 0, 0)); + QWidget* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); + + // Get the drop target for this location + target = DragUtil::GetDropTarget(targetControl, draggedItem, location, + tracker->GetRectangle()); + + // Set up the tracker feedback based on the target + QRect snapTarget; + if (target != 0) + { + snapTarget = target->GetSnapRectangle(); + + tracker->SetCursor(target->GetCursor()); + } + else + { + 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) + { + 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 + QRect currentRectangle = tracker->GetRectangle(); + + if (!(currentRectangle == snapTarget)) + { + tracker->SetRectangle(snapTarget); + } + } - 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 2d79d80b35..f3e5fc7615 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtTracker.h @@ -1,111 +1,129 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYQTTRACKER_H_ #define BERRYQTTRACKER_H_ #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); }; /** * 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 { +class QtTracker : public QObject +{ + Q_OBJECT private: QRubberBand* rubberBand; QtDragManager* dragManager; int cursorOverride; - GuiTk::IControlListener::Events controlEvents; - QHash cursorMap; public: QtTracker(); ~QtTracker(); QRect GetRectangle() const; void SetRectangle(const QRect& rectangle); void SetCursor(CursorType cursor); bool Open(); - void AddControlListener(GuiTk::IControlListener::Pointer listener); - void RemoveControlListener(GuiTk::IControlListener::Pointer listener); + Q_SIGNAL void Moved(QtTracker* tracker, const QPoint& globalPoint); - void HandleMove(const QPoint& globalPoint); +}; + +class QtTrackerMoveListener : public QObject +{ + Q_OBJECT + +public: + QtTrackerMoveListener(Object::Pointer draggedItem, const QRect& sourceBounds, + const QPoint& initialLocation, bool allowSnapping); + + Q_SLOT void Moved(QtTracker* tracker, const QPoint& globalPoint); + +private: + bool allowSnapping; + Object::Pointer draggedItem; + QRect sourceBounds; + QPoint initialLocation; }; } #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 136603bf55..db9039acfa 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, +void QtWidgetsTweaklet::AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { impl.AddSelectionListener(static_cast(widget), listener); } -void QtWidgetsTweaklet::RemoveSelectionListener(void* widget, +void QtWidgetsTweaklet::RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { impl.RemoveSelectionListener(static_cast(widget), listener); } QRect QtWidgetsTweaklet::GetScreenSize(int i) { return impl.GetScreenSize(i); } unsigned int QtWidgetsTweaklet::GetScreenNumber() { return impl.GetScreenNumber(); } int QtWidgetsTweaklet::GetPrimaryScreenNumber() { return impl.GetPrimaryScreenNumber(); } QRect QtWidgetsTweaklet::GetAvailableScreenSize(int i) { return impl.GetAvailableScreenSize(i); } int QtWidgetsTweaklet::GetClosestScreenNumber(const QRect& rect) { return impl.GetClosestScreenNumber(rect); } -//IMenu::Pointer QtWidgetsTweaklet::CreateMenu(void*, IMenu::Style style) +//IMenu::Pointer QtWidgetsTweaklet::CreateMenu(QWidget*, 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, +void QtWidgetsTweaklet::AddControlListener(QWidget* 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, +void QtWidgetsTweaklet::RemoveControlListener(QWidget* 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) +bool QtWidgetsTweaklet::GetEnabled(QWidget* widget) { return impl.GetEnabled(static_cast(widget)); } -void QtWidgetsTweaklet::SetEnabled(void* widget, bool enabled) +void QtWidgetsTweaklet::SetEnabled(QWidget* widget, bool enabled) { impl.SetEnabled(static_cast(widget), enabled); } -void QtWidgetsTweaklet::SetBounds(void* widget, const QRect& bounds) +void QtWidgetsTweaklet::SetBounds(QWidget* widget, const QRect& bounds) { impl.SetBounds(static_cast(widget), bounds); } -QRect QtWidgetsTweaklet::GetBounds(void* widget) +QRect QtWidgetsTweaklet::GetBounds(QWidget* widget) { return impl.GetBounds(static_cast(widget)); } -void QtWidgetsTweaklet::SetVisible(void* widget, bool visible) +void QtWidgetsTweaklet::SetVisible(QWidget* widget, bool visible) { impl.SetVisible(static_cast(widget), visible); } -bool QtWidgetsTweaklet::GetVisible(void* widget) +bool QtWidgetsTweaklet::GetVisible(QWidget* widget) { return impl.GetVisible(static_cast(widget)); } -bool QtWidgetsTweaklet::IsVisible(void* widget) +bool QtWidgetsTweaklet::IsVisible(QWidget* widget) { return impl.IsVisible(static_cast(widget)); } -QRect QtWidgetsTweaklet::GetClientArea(void* widget) +QRect QtWidgetsTweaklet::GetClientArea(QWidget* widget) { return impl.GetClientArea(static_cast(widget)); } -void* QtWidgetsTweaklet::GetParent(void* widget) +QWidget* QtWidgetsTweaklet::GetParent(QWidget* widget) { return impl.GetParent(static_cast(widget)); } -bool QtWidgetsTweaklet::SetParent(void* widget, void* parent) +bool QtWidgetsTweaklet::SetParent(QWidget* widget, QWidget* parent) { return impl.SetParent(static_cast(widget), static_cast(parent)); } -void QtWidgetsTweaklet::SetData(void* widget, const QString& id, Object::Pointer data) +void QtWidgetsTweaklet::SetData(QWidget* widget, const QString& id, Object::Pointer data) { impl.SetData(static_cast(widget), id, data); } -Object::Pointer QtWidgetsTweaklet::GetData(void* widget, const QString& id) +Object::Pointer QtWidgetsTweaklet::GetData(QWidget* widget, const QString& id) { return impl.GetData(static_cast(widget), id); } QPoint QtWidgetsTweaklet::GetCursorLocation() { return impl.GetCursorLocation(); } -void* QtWidgetsTweaklet::GetCursorControl() +QWidget* QtWidgetsTweaklet::GetCursorControl() { return impl.GetCursorControl(); } -void* QtWidgetsTweaklet::FindControl(const QList& shells, const QPoint& location) +QWidget* QtWidgetsTweaklet::FindControl(const QList& shells, const QPoint& location) { return impl.FindControl(shells, location); } -bool QtWidgetsTweaklet::IsChild(void* parentToTest, void* childToTest) +bool QtWidgetsTweaklet::IsChild(QWidget* parentToTest, QWidget* childToTest) { return impl.IsChild(static_cast(parentToTest), static_cast(childToTest)); } -void* QtWidgetsTweaklet::GetFocusControl() +QWidget* QtWidgetsTweaklet::GetFocusControl() { return impl.GetFocusControl(); } -bool QtWidgetsTweaklet::IsReparentable(void* widget) +bool QtWidgetsTweaklet::IsReparentable(QWidget* widget) { return impl.IsReparentable(static_cast(widget)); } -void QtWidgetsTweaklet::MoveAbove(void* widgetToMove, void* widget) +void QtWidgetsTweaklet::MoveAbove(QWidget* widgetToMove, QWidget* widget) { impl.MoveAbove(static_cast(widgetToMove), static_cast(widget)); } -void QtWidgetsTweaklet::MoveBelow(void* widgetToMove, void* widget) +void QtWidgetsTweaklet::MoveBelow(QWidget* widgetToMove, QWidget* widget) { impl.MoveBelow(static_cast(widgetToMove), static_cast(widget)); } -void QtWidgetsTweaklet::Dispose(void* widget) +void QtWidgetsTweaklet::Dispose(QWidget* 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) +QWidget* QtWidgetsTweaklet::CreateComposite(QWidget* 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) +Shell::Pointer QtWidgetsTweaklet::GetShell(QWidget* widget) { return impl.GetShell(static_cast(widget)); } Shell::Pointer QtWidgetsTweaklet::GetActiveShell() { return impl.GetActiveShell(); } -QRect QtWidgetsTweaklet::ToControl(void* coordinateSystem, +QRect QtWidgetsTweaklet::ToControl(QWidget* coordinateSystem, const QRect& toConvert) { return impl.ToControl(static_cast(coordinateSystem), toConvert); } -QPoint QtWidgetsTweaklet::ToControl(void* coordinateSystem, +QPoint QtWidgetsTweaklet::ToControl(QWidget* coordinateSystem, const QPoint& toConvert) { return impl.ToControl(static_cast(coordinateSystem), toConvert); } -QRect QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, +QRect QtWidgetsTweaklet::ToDisplay(QWidget* coordinateSystem, const QRect& toConvert) { return impl.ToDisplay(static_cast(coordinateSystem), toConvert); } -QPoint QtWidgetsTweaklet::ToDisplay(void* coordinateSystem, +QPoint QtWidgetsTweaklet::ToDisplay(QWidget* 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 65bbfdc98d..e777744276 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 AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener); + void RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener); - void AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener); - void RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener); + void AddControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener); + void RemoveControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener); - bool GetEnabled(void* widget); - void SetEnabled(void* widget, bool enabled); + bool GetEnabled(QWidget* widget); + void SetEnabled(QWidget* widget, bool enabled); - void SetBounds(void* widget, const QRect& bounds); - QRect GetBounds(void* widget); + void SetBounds(QWidget* widget, const QRect& bounds); + QRect GetBounds(QWidget* widget); - void SetVisible(void* widget, bool visible); - bool GetVisible(void* widget); - bool IsVisible(void* widget); + void SetVisible(QWidget* widget, bool visible); + bool GetVisible(QWidget* widget); + bool IsVisible(QWidget* widget); - QRect GetClientArea(void* widget); + QRect GetClientArea(QWidget* widget); - void* GetParent(void* widget); - bool SetParent(void* widget, void* parent); + QWidget* GetParent(QWidget* widget); + bool SetParent(QWidget* widget, QWidget* parent); - void SetData(void* widget, const QString& id, Object::Pointer data); - Object::Pointer GetData(void* widget, const QString& id); + void SetData(QWidget* widget, const QString& id, Object::Pointer data); + Object::Pointer GetData(QWidget* widget, const QString& id); - //IMenu::Pointer CreateMenu(void*, IMenu::Style = IMenu::POP_UP); + //IMenu::Pointer CreateMenu(QWidget*, IMenu::Style = IMenu::POP_UP); //IMenu::Pointer CreateMenu(IMenu::Pointer parent); //IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1); QRect GetScreenSize(int i = -1); unsigned int GetScreenNumber(); int GetPrimaryScreenNumber(); QRect GetAvailableScreenSize(int i = -1); int GetClosestScreenNumber(const QRect&); QPoint GetCursorLocation(); - void* GetCursorControl(); - void* FindControl(const QList& shells, const QPoint& location); + QWidget* GetCursorControl(); + 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(void* potentialParent, void* childToTest); + bool IsChild(QWidget* potentialParent, QWidget* 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(); + QWidget* GetFocusControl(); - bool IsReparentable(void* widget); + bool IsReparentable(QWidget* widget); - void MoveAbove(void* widgetToMove, void* widget); - void MoveBelow(void* widgetToMove, void* widget); + void MoveAbove(QWidget* widgetToMove, QWidget* widget); + void MoveBelow(QWidget* widgetToMove, QWidget* widget); - void Dispose(void* widget); + void Dispose(QWidget* widget); Shell::Pointer CreateShell(Shell::Pointer parent, int style); void DisposeShell(Shell::Pointer shell); - void* CreateComposite(void* parent); + QWidget* CreateComposite(QWidget* parent); QList GetShells(); - Shell::Pointer GetShell(void* widget); + Shell::Pointer GetShell(QWidget* widget); Shell::Pointer GetActiveShell(); - QRect ToControl(void* coordinateSystem, + QRect ToControl(QWidget* coordinateSystem, const QRect& toConvert); - QPoint ToControl(void* coordinateSystem, + QPoint ToControl(QWidget* coordinateSystem, const QPoint& toConvert); - QRect ToDisplay(void* coordinateSystem, + QRect ToDisplay(QWidget* coordinateSystem, const QRect& toConvert); - QPoint ToDisplay(void* coordinateSystem, + QPoint ToDisplay(QWidget* 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 6f97075e5d..b9e8c0d8e3 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp @@ -1,433 +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); + selectionListenerMap.remove(widget); delete wrapper; } } QRect QtWidgetsTweakletImpl::GetScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); 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; } QRect QtWidgetsTweakletImpl::GetAvailableScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); if (i < 0) return desktop->screen()->geometry(); return desktop->availableGeometry(i); } int QtWidgetsTweakletImpl::GetClosestScreenNumber(const QRect& r) { QDesktopWidget *desktop = QApplication::desktop(); 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 QRect& bounds) { widget->setGeometry(bounds); } QRect QtWidgetsTweakletImpl::GetBounds(QWidget* widget) { const QRect& geometry = widget->geometry(); 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(); } QRect QtWidgetsTweakletImpl::GetClientArea(QWidget* widget) { return widget->contentsRect(); } -void* QtWidgetsTweakletImpl::GetParent(QWidget* widget) +QWidget* 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); } QPoint QtWidgetsTweakletImpl::GetCursorLocation() { QPoint qpoint = QCursor::pos(); return QPoint(qpoint.x(), qpoint.y()); } QWidget* QtWidgetsTweakletImpl::GetCursorControl() { return QApplication::widgetAt(QCursor::pos()); } 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()); 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); } QRect QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, const QRect& toConvert) { QPoint globalUpperLeft = toConvert.topLeft(); QPoint globalLowerRight = toConvert.bottomRight(); QPoint upperLeft = coordinateSystem->mapFromGlobal(globalUpperLeft); QPoint lowerRight = coordinateSystem->mapFromGlobal(globalLowerRight); return QRect(upperLeft.x(), upperLeft.y(), lowerRight.x() - upperLeft.x(), lowerRight.y() - upperLeft.y()); } QPoint QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, const QPoint& toConvert) { return coordinateSystem->mapFromGlobal(toConvert); } QRect QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, const QRect& toConvert) { QPoint upperLeft = toConvert.topLeft(); QPoint lowerRight = toConvert.bottomRight(); QPoint globalUpperLeft = coordinateSystem->mapToGlobal(upperLeft); QPoint globalLowerRight = coordinateSystem->mapToGlobal(lowerRight); return QRect(globalUpperLeft.x(), globalUpperLeft.y(), globalLowerRight.x() - globalUpperLeft.x(), globalLowerRight.y() - globalUpperLeft.y()); } QPoint QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, const QPoint& toConvert) { 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 d880b1038c..44cfcf8d07 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h @@ -1,156 +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 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 QRect& bounds); QRect GetBounds(QWidget* widget); void SetVisible(QWidget* widget, bool visible); bool GetVisible(QWidget* widget); bool IsVisible(QWidget* widget); QRect GetClientArea(QWidget* widget); - void* GetParent(QWidget* widget); + QWidget* 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); QRect GetScreenSize(int i = -1); unsigned int GetScreenNumber(); int GetPrimaryScreenNumber(); QRect GetAvailableScreenSize(int i = -1); int GetClosestScreenNumber(const QRect&); QPoint GetCursorLocation(); QWidget* GetCursorControl(); 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(); QRect ToControl(QWidget* coordinateSystem, const QRect& toConvert); QPoint ToControl(QWidget* coordinateSystem, const QPoint& toConvert); QRect ToDisplay(QWidget* coordinateSystem, const QRect& toConvert); QPoint ToDisplay(QWidget* coordinateSystem, const QPoint& toConvert); private: - typedef QHash SelectionListenerMap; + typedef QHash SelectionListenerMap; SelectionListenerMap selectionListenerMap; QList shellList; friend class QtShell; }; } #endif /* BERRYQTWIDGETSTWEAKLETIMPL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.cpp index fb2c05d711..d75954a7f6 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.cpp @@ -1,74 +1,74 @@ /*=================================================================== 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 "berryQtWorkbenchPageTweaklet.h" #include #include #include #include namespace berry { QtWorkbenchPageTweaklet::QtWorkbenchPageTweaklet() { } -void* QtWorkbenchPageTweaklet::CreateClientComposite(void* pageControl) +QWidget* QtWorkbenchPageTweaklet::CreateClientComposite(QWidget* pageControl) { QWidget* parent = static_cast(pageControl); QtControlWidget* client = new QtControlWidget(parent, 0); client->setObjectName("ClientComposite"); parent->layout()->addWidget(client); // we have to enable visibility to get a proper layout (see bug #1654) client->setVisible(true); return client; } -void* QtWorkbenchPageTweaklet::CreatePaneControl(void* parent) +QWidget* QtWorkbenchPageTweaklet::CreatePaneControl(QWidget* parent) { QWidget* qParent = static_cast(parent); QtControlWidget* control = new QtControlWidget(qParent, 0); // the object name is used in the global event filter to find // the pane control over which a mouse pressed event occured // --> do not change the object name control->setObjectName("PartPaneControl"); return control; } -Object::Pointer QtWorkbenchPageTweaklet::CreateStatusPart(void* parent, const QString& title, const QString& msg) +Object::Pointer QtWorkbenchPageTweaklet::CreateStatusPart(QWidget* parent, const QString& title, const QString& msg) { Ui::QtStatusPart statusPart; statusPart.setupUi(static_cast(parent)); statusPart.m_TitleLabel->setText(title); statusPart.m_DetailsLabel->setText(msg); return Object::Pointer(0); } IEditorPart::Pointer QtWorkbenchPageTweaklet::CreateErrorEditorPart(const QString& /*partName*/, const QString& /*msg*/) { return IEditorPart::Pointer(0); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h index 0b0ddae882..de9446d400 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h @@ -1,49 +1,49 @@ /*=================================================================== 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 BERRYQTWORKBENCHPAGETWEAKLET_H_ #define BERRYQTWORKBENCHPAGETWEAKLET_H_ #include #include namespace berry { class BERRY_UI_QT QtWorkbenchPageTweaklet : public QObject, public WorkbenchPageTweaklet { Q_OBJECT Q_INTERFACES(berry::WorkbenchPageTweaklet) public: berryObjectMacro(QtWorkbenchPageTweaklet) QtWorkbenchPageTweaklet(); - void* CreateClientComposite(void* pageControl); - void* CreatePaneControl(void* parent); + QWidget* CreateClientComposite(QWidget* pageControl); + QWidget* CreatePaneControl(QWidget* parent); - Object::Pointer CreateStatusPart(void* parent, const QString& title, const QString& msg); + Object::Pointer CreateStatusPart(QWidget* parent, const QString& title, const QString& msg); IEditorPart::Pointer CreateErrorEditorPart(const QString& partName, const QString& msg); }; } #endif /* BERRYQTWORKBENCHPAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp index 058aef6009..e2e1eb8dd3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.cpp @@ -1,444 +1,444 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewReference.h" #include #include "berryUIException.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryPlatformUI.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" #include "berryViewDescriptor.h" #include "berryViewFactory.h" #include "berryViewRegistry.h" #include "berryViewSite.h" #include "berryPartTester.h" #include "berryWorkbenchPlugin.h" #include "berryErrorViewPart.h" namespace berry { ViewReference::ViewReference(ViewFactory* fac, const QString& id, const QString& secId, IMemento::Pointer m) : factory(fac), secondaryId(secId), memento(m) { ViewDescriptor::Pointer desc = this->factory->GetViewRegistry()->Find(id).Cast (); QIcon iDesc; QString title; if (!desc.IsNull()) { iDesc = desc->GetImageDescriptor(); title = desc->GetLabel(); } QString name; if (!memento.IsNull()) { // name = memento.getString(IWorkbenchConstants.TAG_PART_NAME); // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } } if (name.isEmpty()) { name = title; } this->Init(id, "", iDesc, name, ""); //$NON-NLS-1$//$NON-NLS-2$ } void ViewReference::DoDisposePart() { IViewPart::Pointer view = part.Cast (); //WorkbenchPartReference::DoDisposePart(); if (!view.IsNull()) { // Free action bars, pane, etc. //PartSite site = (PartSite) view.getSite(); //ViewActionBars actionBars = (ViewActionBars) site.getActionBars(); // // 3.3 start // //IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getMenuManager()); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getToolBarManager()); // 3.3 end //actionBars.dispose(); // and now dispose the delegates since the // PluginActionContributionItem // can no longer do that // if (actionBuilder != null) { // actionBuilder.dispose(); // actionBuilder = null; // } // Free the site. //site.dispose(); } } IWorkbenchPage::Pointer ViewReference::GetPage() const { return IWorkbenchPage::Pointer(this->factory->GetWorkbenchPage()); } QString ViewReference::GetRegisteredName() { if (!part.IsNull() && !part->GetSite().IsNull()) { return part->GetSite()->GetRegisteredName(); } const IViewRegistry* reg = this->factory->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(this->GetId()); if (!desc.IsNull()) { return desc->GetLabel(); } return this->GetPartName(); } QString ViewReference::GetSecondaryId() { return secondaryId; } IViewPart::Pointer ViewReference::GetView(bool restore) { return this->GetPart(restore).Cast (); } IWorkbenchPart::Pointer ViewReference::CreatePart() { // Check the status of this part IWorkbenchPart::Pointer result; PartInitException* exception = 0; // Try to restore the view -- this does the real work of restoring the // view // try { result = this->CreatePartHelper(); } catch (const PartInitException& e) { exception = e.clone(); } // If unable to create the part, create an error part instead // and pass the error to the status handling facility if (exception != 0) { // IStatus partStatus = exception.getStatus(); // IStatus displayStatus = StatusUtil.newStatus(partStatus, // NLS.bind(WorkbenchMessages.ViewFactory_initException, partStatus.getMessage())); // IStatus logStatus = StatusUtil // .newStatus( // partStatus, // NLS // .bind( // "Unable to create view ID {0}: {1}", getId(), partStatus.getMessage())); //$NON-NLS-1$ // Pass the error to the status handling facility // StatusManager.getManager().handle(logStatus); QString errorTitle = "Unable to create view ID " + this->GetId(); WorkbenchPlugin::Log(errorTitle + ": " + exception->what()); IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find( this->GetId()); QString label = this->GetId(); if (!desc.IsNull()) { label = desc->GetLabel(); } QString errorMsg(exception->what()); delete exception; errorMsg += "
    • Check your shared library for unresolved symbols
    • " "
    • Check your class attribute in your plugin.xml file
    • " "
    • Check your manifest.cpp file
    " "
    For a comprehensive check-list, see http://www.mitk.org/wiki/How_to_fix_your_plug-in_DLL"; ErrorViewPart::Pointer part(new ErrorViewPart(errorTitle, errorMsg)); //PartPane pane = getPane(); IViewReference::Pointer viewRef(this); ViewSite::Pointer site(new ViewSite(viewRef, part, factory->GetWorkbenchPage(), GetId(), PlatformUI::PLUGIN_ID(), label)); //site.setActionBars(new ViewActionBars(factory.page.getActionBars(), // site, (ViewPane) pane)); try { part->Init(site); } catch (const PartInitException& e) { BERRY_ERROR << e.what(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } part->SetPartName(label); - void* parent = pane->GetControl(); + QWidget* parent = pane->GetControl(); try { part->CreatePartControl(parent); } catch (const std::exception& e) { BERRY_ERROR << "Error creating view: " << e.what() << std::endl; // StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } return result; } PartPane::Pointer ViewReference::CreatePane() { IWorkbenchPartReference::Pointer partRef(this); PartPane::Pointer pane(new PartPane(partRef, this->factory->GetWorkbenchPage())); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateViewPane(this, this->factory->GetWorkbenchPage()); } IWorkbenchPart::Pointer ViewReference::CreatePartHelper() { IWorkbenchPart::Pointer result; IMemento::Pointer stateMem; if (!memento.IsNull()) { stateMem = memento->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find(GetId()); if (desc.IsNull()) { throw PartInitException(QString("Could not create view: ") + this->GetId()); } // Create the part pane PartPane::Pointer pane = this->GetPane(); // Create the pane's top-level control pane->CreateControl(factory->GetWorkbenchPage()->GetClientComposite()); QString label = desc->GetLabel(); // debugging only // Things that will need to be disposed if an exception occurs (they are // listed here // in the order they should be disposed) //Composite content = null; IViewPart::Pointer initializedView; ViewSite::Pointer site; //ViewActionBars actionBars = null; // End of things that need to be explicitly disposed from the try block try { IViewPart::Pointer view; view = desc->CreateView(); if (view.IsNull()) return result; this->CreatePartProperties(view); // Create site IViewReference::Pointer viewRef(this); site = new ViewSite(viewRef, view, factory->GetWorkbenchPage(), desc); //actionBars = new ViewActionBars(factory.page.getActionBars(), site, // (ViewPane) pane); //site.setActionBars(actionBars); view->Init(site, stateMem); // Once we've called init, we MUST dispose the view. Remember // the fact that // we've initialized the view in case an exception is thrown. initializedView = view; if (view->GetSite() != site) { throw PartInitException("View initialization failed. Site is incorrect."); } // Create the top-level composite { - void* parent = pane->GetControl(); + QWidget* parent = pane->GetControl(); view->CreatePartControl(parent); } // Install the part's tools and menu { // // 3.3 start // // IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); // menuService.populateContributionManager( // (ContributionManager) site.getActionBars() // .getMenuManager(), "menu:" //$NON-NLS-1$ // + site.getId()); // menuService // .populateContributionManager((ContributionManager) site // .getActionBars().getToolBarManager(), // "toolbar:" + site.getId()); //$NON-NLS-1$ // 3.3 end // actionBuilder = new ViewActionBuilder(); // actionBuilder.readActionExtensions(view); // ActionDescriptor[] actionDescriptors = actionBuilder // .getExtendedActions(); // IKeyBindingService keyBindingService = view.getSite() // .getKeyBindingService(); // // if (actionDescriptors != null) { // for (int i = 0; i < actionDescriptors.length; i++) { // ActionDescriptor actionDescriptor = actionDescriptors[i]; // // if (actionDescriptor != null) { // IAction action = actionDescriptors[i].getAction(); // // if (action != null // && action.getActionDefinitionId() != null) { // keyBindingService.registerAction(action); // } // } // } // } // // site.getActionBars().updateActionBars(); } // The part should now be fully created. Exercise its public // interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave // badly, it's much better // that it does so now while we can still cancel creation of the // part. PartTester::TestView(view); result = view.Cast (); // IConfigurationElement::Pointer element = desc->GetConfigurationElement(); // if (!element.IsNull()) { // factory.page.getExtensionTracker().registerObject( // element.getDeclaringExtension(), view, // IExtensionTracker.REF_WEAK); // } } catch (const ctkException& e) { // if ((e instanceof Error) && !(e instanceof LinkageError)) { // throw (Error) e; // } // An exception occurred. First deallocate anything we've allocated // in the try block (see the top // of the try block for a list of objects that need to be explicitly // disposed) // if (content != null) { // try { // content.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (initializedView != null) { // try { // initializedView.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (site != null) { // try { // site.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (actionBars != null) { // try { // actionBars.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } throw PartInitException(e.what(), e); } catch (const std::exception& e) { throw PartInitException(e.what()); } return result; } IMemento::Pointer ViewReference::GetMemento() { return memento; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.h index e1ad88b644..debf49d75b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewReference.h @@ -1,112 +1,112 @@ /*=================================================================== 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 BERRYVIEWREFERENCE_H_ #define BERRYVIEWREFERENCE_H_ #include "berryIMemento.h" #include "berryWorkbenchPartReference.h" #include "berryIViewReference.h" #include "berryPartPane.h" namespace berry { class ViewFactory; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_internal * */ class ViewReference : public WorkbenchPartReference, public IViewReference { -public: berryObjectMacro(ViewReference); +public: berryObjectMacro(ViewReference) private: const ViewFactory* factory; public: QString secondaryId; private: IMemento::Pointer memento; //private: ViewActionBuilder actionBuilder; public: ViewReference(ViewFactory* factory, const QString& id, const QString& secondaryId, IMemento::Pointer memento); /* * (non-Javadoc) * * @see org.blueberry.ui.internal.WorkbenchPartReference#dispose() */ protected: virtual void DoDisposePart(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPartReference#getPage() */ public: virtual SmartPointer GetPage() const; /* * (non-Javadoc) * * @see org.blueberry.ui.internal.WorkbenchPartReference#getRegisteredName() */ public: virtual QString GetRegisteredName(); /* * (non-Javadoc) * * @see org.blueberry.ui.IViewReference */ public: virtual QString GetSecondaryId(); /* * (non-Javadoc) * * @see org.blueberry.ui.IViewReference#getView(boolean) */ public: virtual IViewPart::Pointer GetView(bool restore); /** * Wrapper for restoring the view. First, this delegates to * busyRestoreViewHelper to do the real work of restoring the view. If * unable to restore the view, this method tries to substitute an error part * and return success. * * @return the created part */ protected: IWorkbenchPart::Pointer CreatePart(); protected: PartPane::Pointer CreatePane(); private: IWorkbenchPart::Pointer CreatePartHelper(); /** * The memento is that last view state saved by the workbench. * * @return the last state that was saved by the workbench. It can return * null. * @since 3.1.1 */ public: virtual IMemento::Pointer GetMemento(); }; } // namespace berry #endif /*BERRYVIEWREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp index 10b29d413b..d41e6deb93 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.cpp @@ -1,292 +1,292 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewSashContainer.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" namespace berry { -ViewSashContainer::ViewSashContainer(WorkbenchPage* page, void* parent) : +ViewSashContainer::ViewSashContainer(WorkbenchPage* page, QWidget* parent) : PartSashContainer("root layout container", page, parent) { } ViewSashContainer::Pointer ViewSashContainer::GetRootContainer() { return ViewSashContainer::Pointer(this); } -void* ViewSashContainer::GetControl() +QWidget* ViewSashContainer::GetControl() { return this->parent; } bool ViewSashContainer::RestoreState(IMemento::Pointer memento) { //TODO ViewSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, null); // bool result = true; // Read the info elements. QList children(memento->GetChildren(WorkbenchConstants::TAG_INFO)); // Create a part ID to part hashtable. QHash mapIDtoPart; // Loop through the info elements. for (int i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; QString partID; childMem->GetString(WorkbenchConstants::TAG_PART, partID); QString relativeID; childMem->GetString(WorkbenchConstants::TAG_RELATIVE, relativeID); int relationship = 0; int left = 0, right = 0; if (!relativeID.isEmpty()) { childMem->GetInteger(WorkbenchConstants::TAG_RELATIONSHIP, relationship); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_LEFT, left); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_RIGHT, right); } QString strFolder; childMem->GetString(WorkbenchConstants::TAG_FOLDER, strFolder); // Create the part. LayoutPart::Pointer part; if (strFolder.isEmpty()) { // this is the editor area part = new PartPlaceholder(partID); } else { PartStack::Pointer folder(new PartStack(page)); folder->SetID(partID); //result.add(folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER))); result &= folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER)); ContainerPlaceholder::Pointer placeholder(new ContainerPlaceholder(partID)); placeholder->SetRealContainer(folder); part = placeholder; } // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active part->SetContainer(ILayoutContainer::Pointer(this)); const int myLeft = left, myRight = right, myRelationship = relationship; LayoutPart::Pointer myPart = part; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.isEmpty()) { this->Add(myPart); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { this->Add(myPart, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = part; } return result; } bool ViewSashContainer::SaveState(IMemento::Pointer memento) { QList relationships = this->ComputeRelation(); bool result = true; // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, null); // Loop through the relationship array. for (int i = 0; i < relationships.size(); ++i) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); if (info.relative) { childMem->PutString(WorkbenchConstants::TAG_RELATIVE, info.relative->GetID()); childMem->PutInteger(WorkbenchConstants::TAG_RELATIONSHIP, info.relationship); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_LEFT, info.left); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_RIGHT, info.right); } // Is this part a folder or a placeholder for one? PartStack::Pointer folder(info.part.Cast()); if (!folder && info.part.Cast()) { LayoutPart::Pointer part = info.part.Cast()->GetRealContainer(); folder = part.Cast(); } // If this is a folder (PartStack) save the contents. if (folder) { childMem->PutString(WorkbenchConstants::TAG_FOLDER, "true"); IMemento::Pointer folderMem(childMem->CreateChild(WorkbenchConstants::TAG_FOLDER)); //result.add(folder.saveState(folderMem)); result = folder->SaveState(folderMem); } } return result; } bool ViewSashContainer::IsStackType(ILayoutContainer::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR); } bool ViewSashContainer::IsPaneType(LayoutPart::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool ViewSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } void ViewSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // Nasty hack: ensure that all views end up inside a tab folder. // Since the view title is provided by the tab folder, this ensures // that views don't get created without a title tab. if (newChild.Cast()) { PartStack::Pointer folder(new PartStack(page)); folder->Add(newChild); newChild = folder; } PartSashContainer::Replace(oldChild, newChild); } -void* ViewSashContainer::CreateParent(void* parentWidget) +QWidget* ViewSashContainer::CreateParent(QWidget* parentWidget) { return parentWidget; } void ViewSashContainer::DisposeParent() { // do nothing } float ViewSashContainer::GetDockingRatio(Object::Pointer dragged, ILayoutContainer::Pointer target) { if (this->IsStackType(target)) { return PartSashContainer::GetDockingRatio(dragged, target); } else { return 0.25f; } } PartStack::Pointer ViewSashContainer::CreateStack() { PartStack::Pointer result(new PartStack(page)); return result; } void ViewSashContainer::SetVisiblePart(ILayoutContainer::Pointer container, PartPane::Pointer visiblePart) { if (container.Cast () != 0) { PartStack::Pointer tabFolder = container.Cast (); tabFolder->SetSelection(visiblePart); } } LayoutPart::Pointer ViewSashContainer::GetVisiblePart( ILayoutContainer::Pointer container) { return container.Cast ()->GetSelection(); } void ViewSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { page->GetActivePerspective()->GetPresentation()->DerefPart(sourcePart); } // void ViewSashContainer::AddChild(const RelationshipInfo& info) // { // LayoutPart child = info.part; // // // Nasty hack: ensure that all views end up inside a tab folder. // // Since the view title is provided by the tab folder, this ensures // // that views don't get created without a title tab. // if (child instanceof ViewPane) // { // ViewStack folder = new ViewStack(page); // folder.add(child); // info.part = folder; // } // // super.addChild(info); // } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.h index 86c0da1324..cb57cea914 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewSashContainer.h @@ -1,127 +1,127 @@ /*=================================================================== 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 BERRYVIEWSASHCONTAINER_H_ #define BERRYVIEWSASHCONTAINER_H_ #include "berryPartSashContainer.h" #include "berryPartStack.h" namespace berry { /** * Represents the top level container. */ class ViewSashContainer : public PartSashContainer { public: berryObjectMacro(ViewSashContainer); - ViewSashContainer(WorkbenchPage* page, void* parent); + ViewSashContainer(WorkbenchPage* page, QWidget* parent); /** * Gets root container for this part. */ ViewSashContainer::Pointer GetRootContainer(); /** * Get the part control. This method may return null. */ - void* GetControl(); + QWidget* GetControl(); /** * @see IPersistablePart */ bool RestoreState(IMemento::Pointer memento); /** * @see IPersistablePart */ bool SaveState(IMemento::Pointer memento); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#isStackType(org.blueberry.ui.internal.LayoutPart) */ bool IsStackType(ILayoutContainer::Pointer toTest); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#isPaneType(org.blueberry.ui.internal.LayoutPart) */ bool IsPaneType(LayoutPart::Pointer toTest); /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#replace(org.blueberry.ui.internal.LayoutPart, org.blueberry.ui.internal.LayoutPart) */ //void Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild); bool AllowsAdd(LayoutPart::Pointer layoutPart); void Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild); protected: /** * Subclasses override this method to specify * the composite to use to parent all children * layout parts it contains. */ - void* CreateParent(void* parentWidget); + QWidget* CreateParent(QWidget* parentWidget); /** * Subclasses override this method to dispose * of any swt resources created during createParent. */ void DisposeParent(); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#getDockingRatio(org.blueberry.ui.internal.LayoutPart, org.blueberry.ui.internal.LayoutPart) */ float GetDockingRatio(Object::Pointer dragged, ILayoutContainer::Pointer target); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#createStack(org.blueberry.ui.internal.LayoutPart) */ PartStack::Pointer CreateStack(); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#setVisiblePart(org.blueberry.ui.internal.ILayoutContainer, org.blueberry.ui.internal.LayoutPart) */ void SetVisiblePart(ILayoutContainer::Pointer container, PartPane::Pointer visiblePart); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#getVisiblePart(org.blueberry.ui.internal.ILayoutContainer) */ LayoutPart::Pointer GetVisiblePart(ILayoutContainer::Pointer container); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#derefPart(org.blueberry.ui.internal.LayoutPart) */ void DerefPart(LayoutPart::Pointer sourcePart); /* (non-Javadoc) * @see org.blueberry.ui.internal.PartSashContainer#addChild(org.blueberry.ui.internal.PartSashContainer.RelationshipInfo) */ //void AddChild(const RelationshipInfo& info); }; } #endif /* BERRYVIEWSASHCONTAINER_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 7d8feced30..04988c47c6 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(); + QWidget* 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() +QWidget* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } bool WorkbenchPage::HasView(const QString& perspectiveId, const QString& viewId) { PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives(); for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++) { SmartPointer p = *it; if (p->GetDesc()->GetId() == perspectiveId) { if (p->ContainsView(viewId)) { return true; } } } return false; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } QList WorkbenchPage::GetEditors() { QList refs = this->GetEditorReferences(); QList result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (QList::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } QList WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } QList WorkbenchPage::GetDirtyParts() { QList result; QList allParts = this->GetAllParts(); for (int i = 0; i < allParts.size(); i++) { IWorkbenchPartReference::Pointer reference = allParts[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0 && part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty()) { result.push_back(saveable); } } } return result; } IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input) { return this->GetEditorManager()->FindEditor(input); } QList WorkbenchPage::FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } QList WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } QString WorkbenchPage::GetLabel() { QString label = ""; // IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input, // IWorkbenchAdapter.class); // if (adapter != 0) // { // label = adapter.getLabel(input); // } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { label = label + " - " + persp->GetDesc()->GetLabel(); } else if (deferredActivePersp != 0) { label = label + " - " + deferredActivePersp->GetLabel(); } return label; } IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective() { if (deferredActivePersp != 0) { return deferredActivePersp; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetDesc(); } else { return IPerspectiveDescriptor::Pointer(0); } } ISelection::ConstPointer WorkbenchPage::GetSelection() const { return selectionService->GetSelection(); } ISelection::ConstPointer WorkbenchPage::GetSelection(const QString& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const QString& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } QList WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return QList(); } } QList WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } QList WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } QList parts; if (persp != 0) { QList refs = persp->GetViewReferences(); for (int i = 0; i < refs.size(); i++) { IViewPart::Pointer part = refs[i]->GetPart(restore).Cast (); if (part != 0) { parts.push_back(part); } } } return parts; } IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() { return IWorkbenchWindow::Pointer(window); } void WorkbenchPage::HideView(IViewReference::Pointer ref) { // Sanity check. if (ref == 0) { return; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } bool promptedForSave = false; IViewPart::Pointer view = ref->GetView(false); if (view != 0) { if (!this->CertifyPart(view)) { return; } // Confirm. if (view.Cast () != 0) { ISaveablePart::Pointer saveable = view.Cast (); if (saveable->IsSaveOnCloseNeeded()) { IWorkbenchWindow::Pointer window = view->GetSite()->GetWorkbenchWindow(); QList partsToSave; partsToSave.push_back(view); bool success = EditorManager::SaveAll(partsToSave, true, true, false, window); if (!success) { // the user cancelled. return; } promptedForSave = true; } } } int refCount = this->GetViewFactory()->GetReferenceCount(ref); SaveablesList* saveablesList = NULL; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = dynamic_cast( actualPart->GetSite()->GetService()); QList partsToClose; partsToClose.push_back(actualPart); postCloseInfo = saveablesList->PreCloseParts(partsToClose, !promptedForSave, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { // cancel return; } } } IWorkbenchPage::Pointer thisPage(this); // Notify interested listeners before the hide window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref, CHANGE_VIEW_HIDE); PartPane::Pointer pane = this->GetPane(ref.Cast ()); pane->SetInLayout(false); this->UpdateActivePart(); if (saveablesList != 0) { saveablesList->PostClose(postCloseInfo); } // Hide the part. persp->HideView(ref); // Notify interested listeners after the hide window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_VIEW_HIDE); } void WorkbenchPage::RefreshActiveView() { this->UpdateActivePart(); } void WorkbenchPage::HideView(IViewPart::Pointer view) { this->HideView(this->GetReference(view).Cast ()); } void WorkbenchPage::Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras) { // Save args. this->window = w; this->input = input; this->composite = 0; this->viewFactory = 0; this->activationList = new ActivationList(this); this->selectionService = new PageSelectionService(this); this->partList.reset(new WorkbenchPagePartList(this->selectionService)); this->stickyViewMan = new StickyViewManager(this); //actionSets = new ActionSetManager(w); deferCount = 0; // Create presentation. this->CreateClientComposite(); editorPresentation = new EditorAreaHelper(this); editorMgr = new EditorManager(WorkbenchWindow::Pointer(window), WorkbenchPage::Pointer(this), editorPresentation); //TODO WorkbenchPage perspective reorder listener? // // add this page as a client to be notified when the UI has re-ordered perspectives // // so that the order can be properly maintained in the receiver. // // E.g. a UI might support drag-and-drop and will need to make this known to ensure // // #saveState and #restoreState do not lose this re-ordering // w.addPerspectiveReorderListener(new IReorderListener() // { // public void WorkbenchPage::reorder(Object perspective, int newLoc) // { // perspList.reorder((IPerspectiveDescriptor)perspective, newLoc); // } // }); if (openExtras) { this->OpenPerspectiveExtras(); } // Get perspective descriptor. if (layoutID != "") { PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( layoutID).Cast (); if (desc == 0) { throw WorkbenchException("Unable to create Perspective " + layoutID + ". There is no corresponding perspective extension."); } Perspective::Pointer persp = this->FindPerspective(desc); if (persp == 0) { persp = this->CreatePerspective(desc, true); } perspList.SetActive(persp); window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc); } // getExtensionTracker() .registerHandler(perspectiveChangeHandler, // ExtensionTracker .createExtensionPointFilter( // getPerspectiveExtensionPoint())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras QString extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); QList descs; foreach (QString id, extras.split(", ", QString::SkipEmptyParts)) { if (id.trimmed().isEmpty()) continue; IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(id); if (desc != 0) { descs.push_back(desc); } } // HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list. // So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared. for (int i = (int) descs.size(); --i >= 0;) { PerspectiveDescriptor::Pointer desc = descs[i].Cast (); if (this->FindPerspective(desc) == 0) { this->CreatePerspective(desc, true); } } } bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); return pane != 0 && pane->GetVisible(); } bool WorkbenchPage::IsEditorAreaVisible() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return false; } return persp->IsEditorAreaVisible(); } bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { //return persp->IsFastView(ref); return false; } else { return false; } } bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsCloseable(ref); } return false; } bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsMoveable(ref); } return false; } bool WorkbenchPage::IsFixedLayout() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsFixedLayout(); } else { return false; } } bool WorkbenchPage::IsSaveNeeded() { return this->GetEditorManager()->IsSaveAllNeeded(); } void WorkbenchPage::OnActivate() { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true); Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->OnActivate(); this->UpdateVisibility(Perspective::Pointer(0), persp); } } void WorkbenchPage::OnDeactivate() { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); if (this->GetActivePerspective() != 0) { this->GetActivePerspective()->OnDeactivate(); } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); } void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) { // Rather than calling editor.setInput on the editor directly, we do it through the part reference. // This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response // to the input change... but if all editors obeyed their API contract, the "else" branch would be // sufficient. IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast () != 0) { EditorReference::Pointer editorRef = ref.Cast (); editorRef->SetInput(input); } else { editor->SetInput(input); } //navigationHistory.markEditor(editor); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { if (input == 0 || editorID == "") { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditor(input, editorID, activate, matchFlags, editorState); } IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor( IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { if (input == 0 || !(editorDescriptor.Cast () != 0)) { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast< EditorDescriptor> (), activate, editorState); // } // }); } IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor, activate, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched( IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { // If an editor already exists for the input, use it. IEditorPart::Pointer editor; // Reuse an existing open editor, unless we are in "new editor tab management" mode editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags); if (editor != 0) { if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID) { if (editor->IsDirty()) { QMessageBox::StandardButton saveFile = QMessageBox::question( this->GetWorkbenchWindow()->GetShell()->GetControl(), "Save", "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel); if (saveFile == QMessageBox::Yes) { // try // { IEditorPart::Pointer editorToSave = editor; // getWorkbenchWindow().run(false, false, // new IRunnableWithProgress() // { // public void WorkbenchPage::run(IProgressMonitor monitor) // throws InvocationTargetException, // InterruptedException // { //TODO progress monitor editorToSave->DoSave();//monitor); // } // }); // } // catch (InvocationTargetException& e) // { // throw(RuntimeException) e->GetTargetException(); // } // catch (InterruptedException& e) // { // return 0; // } } else if (saveFile == QMessageBox::Cancel) { return IEditorPart::Pointer(0); } } } else { // // do the IShowEditorInput notification before showing the editor // // to reduce flicker // if (editor.Cast () != 0) // { // ((IShowEditorInput) editor).showEditorInput(input); // } this->ShowEditor(activate, editor); return editor; } } // Otherwise, create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor( editorID, input, true, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { IEditorPart::Pointer editor; // Create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor, input, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } void WorkbenchPage::OpenEmptyTab() { IEditorPart::Pointer editor; EditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEmptyTab().Cast (); if (ref != 0) { editor = ref->GetEmptyEditor( dynamic_cast (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor( EditorRegistry::EMPTY_EDITOR_ID).Cast ()); } if (editor != 0) { this->SetEditorAreaVisible(true); this->Activate(editor); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } } void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor) { this->SetEditorAreaVisible(true); if (activate) { //zoomOutIfNecessary(editor); this->Activate(editor); } else { this->BringToTop(editor); } } bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor) { WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast< WorkbenchPartReference> (); return ref != 0 && ref->IsPinned(); } /** * Removes an IPartListener from the part service. */ void WorkbenchPage::RemovePartListener(IPartListener* l) { partList->GetPartService()->RemovePartListener(l); } /** * Implements IWorkbenchPage * * @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener) * @since 2.0 * @deprecated individual views should store a working set if needed and * register a property change listener directly with the * working set manager to receive notification when the view * working set is removed. */ // void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) { // propertyChangeListeners.remove(listener); // } void WorkbenchPage::RemoveSelectionListener(ISelectionListener* listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener(ISelectionListener* listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemovePostSelectionListener(partId, listener); } void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } // Real work. this->SetActivePart(part); } /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ void WorkbenchPage::ResetPerspective() { // Run op in busy cursor. // Use set redraw to eliminate the "flash" that can occur in the // coolbar as the perspective is reset. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // try // { // mgr.getControl2().setRedraw(false); // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusyResetPerspective(); // } // }); // }finally // { // mgr.getControl2().setRedraw(true); // } } bool WorkbenchPage::RestoreState(IMemento::Pointer memento, const IPerspectiveDescriptor::Pointer activeDescriptor) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { this->DeferUpdates(true); // }}); try { // Restore working set QString pageName; memento->GetString(WorkbenchConstants::TAG_LABEL, pageName); // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH)) // { // label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$ // } try { //UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$ // MultiStatus result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToRestorePerspective, // pageName), 0); bool result = true; // String workingSetName = memento .getString( // IWorkbenchConstants.TAG_WORKING_SET); // if (workingSetName != 0) // { // AbstractWorkingSetManager // workingSetManager = // (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager(); // setWorkingSet(workingSetManager.getWorkingSet(workingSetName)); // } // // IMemento workingSetMem = memento .getChild( // IWorkbenchConstants.TAG_WORKING_SETS); // if (workingSetMem != 0) // { // QList workingSetChildren = // workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET); // List workingSetList = new ArrayList(workingSetChildren.length); // for (int i = 0; i < workingSetChildren.length; i++) // { // IWorkingSet // set = // getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet( // workingSetChildren[i].getID()); // if (set != 0) // { // workingSetList.add(set); // } // } // // workingSets = (IWorkingSet[]) workingSetList .toArray( // new IWorkingSet[workingSetList.size()]); // } // // aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID); // // IWorkingSet setWithId = // window.getWorkbench().getWorkingSetManager().getWorkingSet( // aggregateWorkingSetId); // // // check to see if the set has already been made and assign it if it has // if (setWithId.Cast () != 0) // { // aggregateWorkingSet = (AggregateWorkingSet) setWithId; // } // Restore editor manager. IMemento::Pointer childMem = memento->GetChild( WorkbenchConstants::TAG_EDITORS); //result.merge(getEditorManager().restoreState(childMem)); result &= this->GetEditorManager()->RestoreState(childMem); childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS); if (childMem) { //result.merge(getViewFactory().restoreState(childMem)); result &= this->GetViewFactory()->RestoreState(childMem); } // Get persp block. childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES); QString activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); QString activePartSecondaryID; if (!activePartID.isEmpty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.isEmpty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } QString activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. QList perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; IPerspectiveDescriptor::Pointer validPersp; for (int i = 0; i < perspMems.size(); i++) { IMemento::Pointer current = perspMems[i]; // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { Perspective::Pointer persp(new Perspective( PerspectiveDescriptor::Pointer(0), WorkbenchPage::Pointer(this))); //result.merge(persp.restoreState(current)); result &= persp->RestoreState(current); IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc.IsNotNull()) { validPersp=desc; } else { IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->CreatePerspective("Hallo",validPersp); } if (desc == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); //berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry()->Add window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc); // } // }); } bool restoreActivePerspective = false; if (!activeDescriptor) { restoreActivePerspective = true; } else if (activePerspective && activePerspective->GetDesc() == activeDescriptor) { restoreActivePerspective = true; } else { restoreActivePerspective = false; activePerspective = this->CreatePerspective(activeDescriptor.Cast< PerspectiveDescriptor> (), true); if (activePerspective == 0) { // result .merge( // new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.Workbench_showPerspectiveError, // activeDescriptor.getId()), 0)); result &= false; } } perspList.SetActive(activePerspective); // Make sure we have a valid perspective to work with, // otherwise return. activePerspective = perspList.GetActive(); if (activePerspective == 0) { activePerspective = perspList.GetNextActive(); perspList.SetActive(activePerspective); } if (activePerspective && restoreActivePerspective) { //result.merge(activePerspective.restoreState()); result &= activePerspective->RestoreState(); } if (activePerspective) { Perspective::Pointer myPerspective = activePerspective; QString myActivePartId = activePartID; QString mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.isEmpty()) { IWorkbenchPartReference::Pointer ref = myPerspective->FindView( myActivePartId, mySecondaryId); if (ref) { activationList->SetActive(ref); } } // }}); } // childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY); // if (childMem) // { // navigationHistory.restoreState(childMem); // } // else if (GetActiveEditor()) // { // navigationHistory.markEditor(getActiveEditor()); // } // // restore sticky view state stickyViewMan->Restore(memento); // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); return result; } catch (...) { // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ throw ; } } catch (...) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); throw; } } bool WorkbenchPage::SaveAllEditors(bool confirm) { return this->SaveAllEditors(confirm, false); } bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources) { return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources); } bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm) { // Do not certify part do allow editors inside a multipageeditor to // call this. return this->GetEditorManager()->SavePart(saveable, part, confirm); } bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm) { return this->SavePart(editor, editor, confirm); } /** * Saves the current perspective. */ void WorkbenchPage::SavePerspective() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDesc(); } /** * Saves the perspective. */ void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc(); // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDescAs(newDesc); window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc); } /** * Save the state of the page. */ bool WorkbenchPage::SaveState(IMemento::Pointer memento) { // // We must unzoom to get correct layout. // if (isZoomed()) // { // zoomOut(); // } // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToSavePerspective, // getLabel()), 0); bool result = true; // Save editor manager. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS); //result.merge(editorMgr.saveState(childMem)); result &= editorMgr->SaveState(childMem); childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS); //result.merge(getViewFactory().saveState(childMem)); result &= this->GetViewFactory()->SaveState(childMem); // Create persp block. childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES); if (this->GetPerspective()) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, this->GetPerspective()->GetId()); } if (this->GetActivePart() != 0) { if (this->GetActivePart().Cast ()) { IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast(); if (ref) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, ViewFactory::GetKey(ref)); } } else { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, this->GetActivePart()->GetSite()->GetId()); } } // Save each perspective in opened order for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { IMemento::Pointer gChildMem = childMem->CreateChild( WorkbenchConstants::TAG_PERSPECTIVE); //result.merge(persp.saveState(gChildMem)); result &= (*itr)->SaveState(gChildMem); } // // Save working set if set // if (workingSet != 0) // { // memento.putString(IWorkbenchConstants.TAG_WORKING_SET, // workingSet .getName()); // } // // IMemento workingSetMem = memento .createChild( // IWorkbenchConstants.TAG_WORKING_SETS); // for (int i = 0; i < workingSets.length; i++) // { // workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET, // workingSets[i].getName()); // } // // if (aggregateWorkingSetId != 0) // { // memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId); // } // // navigationHistory.saveState(memento .createChild( // IWorkbenchConstants.TAG_NAVIGATION_HISTORY)); // // save the sticky activation state stickyViewMan->Save(memento); return result; } QString WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } QString WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { return "0"; //$NON-NLS-1$ } return ref->GetId(); } void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize it. if (this->GetActivePart() == newPart) { return; } if (partBeingActivated != 0) { if (partBeingActivated->GetPart(false) != newPart) { WorkbenchPlugin::Log(ctkRuntimeException( QString("WARNING: Prevented recursive attempt to activate part ") + this->GetId(newPart) + " while still in the middle of activating part " + this->GetId( partBeingActivated))); } return; } //No need to change the history if the active editor is becoming the // active part // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.ACTIVATE_PART)) // { // label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$ // } try { IWorkbenchPartReference::Pointer partref = this->GetReference(newPart); IWorkbenchPartReference::Pointer realPartRef; if (newPart != 0) { IWorkbenchPartSite::Pointer site = newPart->GetSite(); if (site.Cast () != 0) { realPartRef = site.Cast ()->GetPane()->GetPartReference(); } } partBeingActivated = realPartRef; //UIStats.start(UIStats.ACTIVATE_PART, label); // Notify perspective. It may deactivate fast view. Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->PartActivated(newPart); } // Deactivate old part IWorkbenchPart::Pointer oldPart = this->GetActivePart(); if (oldPart != 0) { this->DeactivatePart(oldPart); } // Set active part. if (newPart != 0) { activationList->SetActive(newPart); if (newPart.Cast () != 0) { this->MakeActiveEditor(realPartRef.Cast ()); } } this->ActivatePart(newPart); actionSwitcher.UpdateActivePart(newPart); partList->SetActivePart(partref); } catch (std::exception& e) { partBeingActivated = 0; // Object blame = newPart == 0 ? (Object) this : newPart; // UIStats.end(UIStats.ACTIVATE_PART, blame, label); throw e; } partBeingActivated = 0; } void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } if (showEditorArea == persp->IsEditorAreaVisible()) { return; } // // If parts change always update zoom. // if (isZoomed()) // { // zoomOut(); // } // Update editor area visibility. IWorkbenchPage::Pointer thisPage(this); if (showEditorArea) { persp->ShowEditorArea(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_SHOW); } else { persp->HideEditorArea(); this->UpdateActivePart(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_HIDE); } } /** * Sets the layout of the page. Assumes the new perspective is not 0. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp) { // Don't do anything if already active layout Perspective::Pointer oldPersp = this->GetActivePerspective(); if (oldPersp == newPersp) { return; } window->LargeUpdateStart(); std::exception exc; bool exceptionOccured = false; try { IWorkbenchPage::Pointer thisPage(this); if (oldPersp != 0) { // fire the pre-deactivate window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc()); } if (newPersp != 0) { bool status = newPersp->RestoreState(); if (!status) { QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; QMessageBox::critical(reinterpret_cast(this->GetWorkbenchWindow()->GetShell()->GetControl()), title, msg); } } // Deactivate the old layout if (oldPersp != 0) { oldPersp->OnDeactivate(); // Notify listeners of deactivation window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc()); } // Activate the new layout perspList.SetActive(newPersp); if (newPersp != 0) { newPersp->OnActivate(); // Notify listeners of activation window->FirePerspectiveActivated(thisPage, newPersp->GetDesc()); } this->UpdateVisibility(oldPersp, newPersp); // Update the window //TODO action sets //window->UpdateActionSets(); // Update sticky views stickyViewMan->Update(oldPersp, newPersp); } catch (std::exception& e) { exc = e; exceptionOccured = true; } window->LargeUpdateEnd(); if (newPersp == 0) { return; } IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc(); if (desc == 0) { return; } if (dirtyPerspectives.erase(desc->GetId())) { this->SuggestReset(); } if (exceptionOccured) throw exc; } void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp, Perspective::Pointer newPersp) { // Flag all parts in the old perspective QList oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (int i = 0; i < oldRefs.size(); i++) { PartPane::Pointer pane = oldRefs[i].Cast ()->GetPane(); pane->SetInLayout(false); } } PerspectiveHelper* pres = 0; // Make parts in the new perspective visible if (newPersp != 0) { pres = newPersp->GetPresentation(); QList newRefs = newPersp->GetViewReferences(); for (int i = 0; i < newRefs.size(); i++) { WorkbenchPartReference::Pointer ref = newRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres->IsPartVisible(ref)) { activationList->BringToTop(ref); } pane->SetInLayout(true); } } this->UpdateActivePart(); // Hide any parts in the old perspective that are no longer visible for (int i = 0; i < oldRefs.size(); i++) { WorkbenchPartReference::Pointer ref = oldRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres == 0 || !pres->IsPartVisible(ref)) { pane->SetVisible(false); } } } /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc) { if (this->GetPerspective() == desc) { return; } // // Going from multiple to single rows can make the coolbar // // and its adjacent views appear jumpy as perspectives are // // switched. Turn off redraw to help with this. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); std::exception exc; bool exceptionOccured = false; try { //mgr.getControl2().setRedraw(false); //getClientComposite().setRedraw(false); // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusySetPerspective(desc); // } // }); } catch (std::exception& e) { exc = e; exceptionOccured = true; } // getClientComposite().setRedraw(true); // mgr.getControl2().setRedraw(true); IWorkbenchPart::Pointer part = this->GetActivePart(); if (part != 0) { part->SetFocus(); } if (exceptionOccured) throw exc; } PartService* WorkbenchPage::GetPartService() { return dynamic_cast (partList->GetPartService()); } void WorkbenchPage::ResetToolBarLayout() { // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // mgr.resetItemOrder(); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID, const QString& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.indexOf(ViewFactory::ID_SEP) != -1) { throw ctkInvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw ctkInvalidArgumentException("Illegal view mode"); } // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { // try // { return this->BusyShowView(viewID, secondaryID, mode); // } catch (PartInitException& e) // { // result = e; // } // } // }); } bool WorkbenchPage::CertifyMode(int mode) { if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE) return true; return false; } QList WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } QList WorkbenchPage::GetOpenPerspectives() { QList opened = perspList.GetOpenedPerspectives(); QList result; for (QList::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { QListIterator iter(perspList.GetSortedPerspectives()); iter.toBack(); while(iter.hasPrevious()) { Perspective::Pointer p = iter.previous(); if (p->ContainsView(part)) { return p; } }; // we should never get here return Perspective::Pointer(0); } QList WorkbenchPage::GetSortedPerspectives() { QList sortedArray = perspList.GetSortedPerspectives(); QList result; for (QList::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetSortedParts() { //return partList->GetParts(this->GetViewReferences()); return activationList->GetParts(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetReference( IWorkbenchPart::Pointer part) { if (part == 0) { return IWorkbenchPartReference::Pointer(0); } IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } PartSite::Pointer partSite = site.Cast (); PartPane::Pointer pane = partSite->GetPane(); return partSite->GetPartReference(); } // for dynamic UI void WorkbenchPage::AddPerspective(Perspective::Pointer persp) { perspList.Add(persp); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveOpened(thisPage, persp->GetDesc()); } QList WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return QList(); } ILayoutContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); QList list; ILayoutContainer::ChildrenType children = folder->GetChildren(); for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer stackablePart = *childIter; if (stackablePart.Cast () != 0) { IViewReference::Pointer view = stackablePart.Cast ()->GetPartReference().Cast< IViewReference> (); if (view != 0) { list.push_back(view); } } } // sort the list by activation order (most recently activated first) std::sort(list.begin(), list.end(), ActivationOrderPred(activationList)); return list; } QList result; result.push_back(this->GetReference(part).Cast ()); return result; } QList WorkbenchPage::GetViewStack( IViewPart::Pointer part) { QList refStack = this->GetViewReferenceStack( part); QList result; for (int i = 0; i < refStack.size(); i++) { IViewPart::Pointer next = refStack[i]->GetView(false); if (next != 0) { result.push_back(next); } } return result; } void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height) { SashInfo sashInfo; PartPane::Pointer pane = part->GetSite().Cast ()->GetPane(); ILayoutContainer::Pointer container = pane->GetContainer(); LayoutTree::Pointer tree = this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find( container.Cast ()); // retrieve our layout sashes from the layout tree this->FindSashParts(tree, pane->FindSashes(), sashInfo); // first set the width int deltaWidth = width - pane->GetBounds().width(); if (sashInfo.right != 0) { QRect rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x()) - rightBounds.x()) / rightBounds.width()); // complete the resize sashInfo.rightNode->SetBounds(rightBounds); } else if (sashInfo.left != 0) { QRect leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x() - deltaWidth) - leftBounds.x()) / leftBounds.width()); // complete the resize sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds()); } // next set the height int deltaHeight = height - pane->GetBounds().height(); if (sashInfo.bottom != 0) { QRect bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y()) - bottomBounds.y()) / bottomBounds.height()); // complete the resize sashInfo.bottomNode->SetBounds(bottomBounds); } else if (sashInfo.top != 0) { QRect topBounds = sashInfo.topNode->GetBounds(); // set the ratio sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y() - deltaHeight) - topBounds.y()) / topBounds.height()); // complete the resize sashInfo.topNode->SetBounds(topBounds); } } void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree, const PartPane::Sashes& sashes, SashInfo& info) { LayoutTree::Pointer parent(tree->GetParent()); if (parent == 0) { return; } if (parent->part.Cast () != 0) { // get the layout part sash from this tree node LayoutPartSash::Pointer sash = parent->part.Cast (); // make sure it has a sash control - void* control = sash->GetControl(); + QWidget* 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/berryWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h index 9e06de5a48..cc8746e90e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h @@ -1,1813 +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. ===================================================================*/ #ifndef BERRYWORKBENCHPAGE_H_ #define BERRYWORKBENCHPAGE_H_ #include #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPartReference.h" #include "berryIReusableEditor.h" #include "berryILayoutContainer.h" #include "berryIStickyViewManager.h" #include "berryWorkbenchPagePartList.h" #include "berryWorkbenchPartReference.h" #include "berryPageSelectionService.h" #include "berryEditorManager.h" #include "berryViewFactory.h" #include "berryPartPane.h" #include namespace berry { struct IExtensionPoint; //class PartPane; //class PartPane::Sashes; class EditorAreaHelper; class WorkbenchWindow; class Perspective; class PerspectiveHelper; class PerspectiveDescriptor; class LayoutPartSash; class LayoutTree; class LayoutTreeNode; class PartService; /** * \ingroup org_blueberry_ui_internal * * A collection of views and editors in a workbench. */ class BERRY_UI_QT WorkbenchPage: public IWorkbenchPage { public: berryObjectMacro(WorkbenchPage); protected: //TODO Weakpointer WorkbenchWindow* window; friend class ViewFactory; friend class WorkbenchWindow; friend class EditorAreaHelper; friend class WWinPartService; private: /** * Manages editor contributions and action set part associations. */ class ActionSwitcher { private: IWorkbenchPart::WeakPtr activePart; IEditorPart::WeakPtr topEditor; /** * Updates the contributions given the new part as the active part. * * @param newPart * the new active part, may be null */ public: void UpdateActivePart(IWorkbenchPart::Pointer newPart); /** * Updates the contributions given the new part as the topEditor. * * @param newEditor * the new top editor, may be null */ public: void UpdateTopEditor(IEditorPart::Pointer newEditor); /** * Activates the contributions of the given part. If enable * is true the contributions are visible and enabled, * otherwise they are disabled. * * @param part * the part whose contributions are to be activated * @param enable * true the contributions are to be enabled, * not just visible. */ private: void ActivateContributions(IWorkbenchPart::Pointer part, bool enable); /** * Deactivates the contributions of the given part. If remove * is true the contributions are removed, otherwise they * are disabled. * * @param part * the part whose contributions are to be deactivated * @param remove * true the contributions are to be removed, * not just disabled. */ private: void DeactivateContributions(IWorkbenchPart::Pointer part, bool remove); }; class ActivationList { public: //List of parts in the activation order (oldest first) typedef std::deque PartListType; typedef std::deque::iterator PartListIter; typedef std::deque::reverse_iterator PartListReverseIter; private: PartListType parts; WorkbenchPage* page; public: ActivationList(WorkbenchPage* page); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer part); /* * Ensures that the given part appears AFTER any other part in the same * container. */ void BringToTop(SmartPointer ref); /* * Returns the last (most recent) iterator (index) of the given container in the activation list, or returns * end() if the given container does not appear in the activation list. */ PartListIter LastIndexOfContainer(SmartPointer container); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer ref); /* * Add the active part to the beginning of the list. */ void Add(SmartPointer ref); /* * Return the active part. Filter fast views. */ SmartPointer GetActive(); /* * Return the previously active part. Filter fast views. */ SmartPointer GetPreviouslyActive(); SmartPointer GetActiveReference(bool editorsOnly); /* * Retuns the index of the part within the activation list. The higher * the index, the more recently it was used. */ PartListIter IndexOf(SmartPointer part); /* * Returns the index of the part reference within the activation list. * The higher the index, the more recent it was used. */ PartListIter IndexOf(SmartPointer ref); /* * Remove a part from the list */ bool Remove(SmartPointer ref); /* * Returns the topmost editor on the stack, or null if none. */ SmartPointer GetTopEditor(); /* * Returns the editors in activation order (oldest first). */ QList > GetEditors(); /* * Return a list with all parts (editors and views). */ QList > GetParts(); private: SmartPointer GetActive(PartListIter start); SmartPointer GetActiveReference(PartListIter start, bool editorsOnly); /* * Find a part in the list starting from the end and filter * and views from other perspectives. Will filter fast views * unless 'includeActiveFastViews' is true; */ SmartPointer GetActiveReference(PartListIter start, bool editorsOnly, bool skipPartsObscuredByZoom); }; /** * Helper class to keep track of all opened perspective. Both the opened * and used order is kept. */ struct PerspectiveList { public: typedef QList > PerspectiveListType; typedef PerspectiveListType::iterator iterator; private: /** * List of perspectives in the order they were opened; */ PerspectiveListType openedList; /** * List of perspectives in the order they were used. Last element is * the most recently used, and first element is the least recently * used. */ PerspectiveListType usedList; /** * The perspective explicitly set as being the active one */ SmartPointer active; void UpdateActionSets(SmartPointer oldPersp, SmartPointer newPersp); public: /** * Creates an empty instance of the perspective list */ PerspectiveList(); /** * Update the order of the perspectives in the opened list * * @param perspective * @param newLoc */ void Reorder(IPerspectiveDescriptor::Pointer perspective, int newLoc); /** * Return all perspectives in the order they were activated. * * @return an array of perspectives sorted by activation order, least * recently activated perspective last. */ PerspectiveListType GetSortedPerspectives(); /** * Adds a perspective to the list. No check is done for a duplicate when * adding. * @param perspective the perspective to add * @return boolean true if the perspective was added */ bool Add(SmartPointer perspective); /** * Returns an iterator on the perspective list in the order they were * opened. */ PerspectiveListType::iterator Begin(); PerspectiveListType::iterator End(); /** * Returns an array with all opened perspectives */ PerspectiveListType GetOpenedPerspectives(); /** * Removes a perspective from the list. */ bool Remove(SmartPointer perspective); /** * Swap the opened order of old perspective with the new perspective. */ void Swap(SmartPointer oldPerspective, SmartPointer newPerspective); /** * Returns whether the list contains any perspectives */ bool IsEmpty(); /** * Returns the most recently used perspective in the list. */ SmartPointer GetActive(); /** * Returns the next most recently used perspective in the list. */ SmartPointer GetNextActive(); /** * Returns the number of perspectives opened */ PerspectiveListType::size_type Size(); /** * Marks the specified perspective as the most recently used one in the * list. */ void SetActive(SmartPointer perspective); }; IAdaptable* input; - void* composite; + QWidget* composite; //Could be delete. This information is in the active part list; ActivationList* activationList; EditorManager* editorMgr; EditorAreaHelper* editorPresentation; //ListenerList propertyChangeListeners = new ListenerList(); PageSelectionService* selectionService; QScopedPointer partList; // = new WorkbenchPagePartList(selectionService); //IActionBars actionBars; ViewFactory* viewFactory; PerspectiveList perspList; SmartPointer deferredActivePersp; //NavigationHistory navigationHistory = new NavigationHistory(this); IStickyViewManager::Pointer stickyViewMan; /** * Returns true if perspective with given id contains view with given id */ bool HasView(const QString& perspectiveId, const QString& viewId); /** * If we're in the process of activating a part, this points to the new part. * Otherwise, this is null. */ IWorkbenchPartReference::Pointer partBeingActivated; /** * Contains a list of perspectives that may be dirty due to plugin * installation and removal. */ std::set dirtyPerspectives; ActionSwitcher actionSwitcher; //IExtensionTracker tracker; // Deferral count... delays disposing parts and sending certain events if nonzero int deferCount; // Parts waiting to be disposed QList pendingDisposals; SmartPointer GetPerspectiveExtensionPoint(); public: /** * Constructs a new page with a given perspective and input. * * @param w * the parent window * @param layoutID * must not be null * @param input * the page input * @throws WorkbenchException * on null layout id */ WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input); /** * Constructs a page. restoreState(IMemento) should be * called to restore this page from data stored in a persistance file. * * @param w * the parent window * @param input * the page input * @throws WorkbenchException */ WorkbenchPage(WorkbenchWindow* w, IAdaptable* input); ~WorkbenchPage(); /** * Activates a part. The part will be brought to the front and given focus. * * @param part * the part to activate */ void Activate(IWorkbenchPart::Pointer part); /** * Activates a part. The part is given focus, the pane is hilighted. */ private: void ActivatePart(const IWorkbenchPart::Pointer part); /** * Adds an IPartListener to the part service. */ public: void AddPartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(const QString& partId, ISelectionListener* listener); private: ILayoutContainer::Pointer GetContainer(IWorkbenchPart::Pointer part); private: ILayoutContainer::Pointer GetContainer(IWorkbenchPartReference::Pointer part); private: SmartPointer GetPane(IWorkbenchPart::Pointer part); private: SmartPointer GetPane(IWorkbenchPartReference::Pointer part); /** * Brings a part to the front of its stack. Does not update the active part or * active editor. This should only be called if the caller knows that the part * is not in the same stack as the active part or active editor, or if the caller * is prepared to update activation after the call. * * @param part */ private: bool InternalBringToTop(IWorkbenchPartReference::Pointer part); /** * Moves a part forward in the Z order of a perspective so it is visible. * If the part is in the same stack as the active part, the new part is * activated. * * @param part * the part to bring to move forward */ public: void BringToTop(IWorkbenchPart::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. * * Assumes the busy cursor is active. */ private: void BusyResetPerspective(); /** * Implements setPerspective. * * Assumes that busy cursor is active. * * @param desc * identifies the new perspective. */ private: void BusySetPerspective(IPerspectiveDescriptor::Pointer desc); /** * Removes the perspective which match the given description. * * @param desc * identifies the perspective to be removed. */ public: void RemovePerspective(IPerspectiveDescriptor::Pointer desc); /** * Shows a view. * * Assumes that a busy cursor is active. */ protected: IViewPart::Pointer BusyShowView(const QString& viewID, const QString& secondaryID, int mode); /* * Performs showing of the view in the given mode. */ private: void BusyShowView(IViewPart::Pointer part, int mode); /** * Returns whether a part exists in the current page. */ private: bool CertifyPart(IWorkbenchPart::Pointer part); /** * Closes the perspective. */ public: bool Close(); /** * See IWorkbenchPage */ public: bool CloseAllSavedEditors(); /** * See IWorkbenchPage */ public: bool CloseAllEditors(bool save); private: void UpdateActivePart(); /** * Makes the given part active. Brings it in front if necessary. Permits null * (indicating that no part should be active). * * @since 3.1 * * @param ref new active part (or null) */ private: void MakeActive(IWorkbenchPartReference::Pointer ref); /** * Makes the given editor active. Brings it to front if necessary. Permits null * (indicating that no editor is active). * * @since 3.1 * * @param ref the editor to make active, or null for no active editor */ private: void MakeActiveEditor(IEditorReference::Pointer ref); /** * See IWorkbenchPage */ public: bool CloseEditors(const QList& refArray, bool save); /** * Enables or disables listener notifications. This is used to delay listener notifications until the * end of a public method. * * @param shouldDefer */ private: void DeferUpdates(bool shouldDefer); private: void StartDeferring(); private: void HandleDeferredEvents(); private: bool IsDeferred(); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorReference::Pointer editorRef, bool save); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorPart::Pointer editor, bool save); /** * Closes current perspective. If last perspective, then entire page * is closed. * * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ public: void CloseCurrentPerspective(bool saveParts, bool closePage); /** * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) */ public: void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage); /** * Closes the specified perspective. If last perspective, then entire page * is closed. * * @param persp * the perspective to be closed * @param saveParts * whether the parts that are being closed should be saved * (editors if last perspective, views if not shown in other * parspectives) */ /* package */ protected: void ClosePerspective(SmartPointer persp, bool saveParts, bool closePage); /** * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) */ public: void CloseAllPerspectives(bool saveEditors, bool closePage); /** * Creates the client composite. */ private: void CreateClientComposite(); /** * Creates a new view set. Return null on failure. * * @param desc the perspective descriptor * @param notify whether to fire a perspective opened event */ private: SmartPointer CreatePerspective(SmartPointer desc, bool notify); /** * This is called by child objects after a part has been added to the page. * The page will in turn notify its listeners. */ /* package */ protected: void PartAdded(WorkbenchPartReference::Pointer ref); /** * This is called by child objects after a part has been added to the page. * The part will be queued for disposal after all listeners have been notified */ /* package */ protected: void PartRemoved(WorkbenchPartReference::Pointer ref); private: void DisposePart(WorkbenchPartReference::Pointer ref); /** * Deactivates a part. The pane is unhilighted. */ private: void DeactivatePart(IWorkbenchPart::Pointer part); /** * Detaches a view from the WorkbenchWindow. */ public: void DetachView(IViewReference::Pointer ref); /** * Removes a detachedwindow. */ public: void AttachView(IViewReference::Pointer ref); /** * Dispose a perspective. * * @param persp the perspective descriptor * @param notify whether to fire a perspective closed event */ private: void DisposePerspective(SmartPointer persp, bool notify); /** * Returns the first view manager with given ID. */ public: SmartPointer FindPerspective(IPerspectiveDescriptor::Pointer desc); /** * See IWorkbenchPage@findView. */ public: IViewPart::Pointer FindView(const QString& id); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const QString& viewId); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId); /** * Notify property change listeners about a property change. * * @param changeId * the change id * @param oldValue * old property value * @param newValue * new property value */ //private: void FirePropertyChange(String changeId, Object oldValue, // Object newValue) { // // UIListenerLogging.logPagePropertyChanged(this, changeId, oldValue, newValue); // // Object[] listeners = propertyChangeListeners.getListeners(); // PropertyChangeEvent event = new PropertyChangeEvent(this, changeId, // oldValue, newValue); // // for (int i = 0; i < listeners.length; i++) { // ((IPropertyChangeListener) listeners[i]).propertyChange(event); // } // } /** * @see IWorkbenchPage */ public: IEditorPart::Pointer GetActiveEditor(); /** * Returns the reference for the active editor, or null * if there is no active editor. * * @return the active editor reference or null */ public: IEditorReference::Pointer GetActiveEditorReference(); /* * (non-Javadoc) Method declared on IPartService */ public: IWorkbenchPart::Pointer GetActivePart(); /* * (non-Javadoc) Method declared on IPartService */ public: IWorkbenchPartReference::Pointer GetActivePartReference(); /** * Returns the active perspective for the page, null if * none. */ public: SmartPointer GetActivePerspective(); /** * Returns the client composite. */ public: - void* GetClientComposite(); + QWidget* GetClientComposite(); // for dynamic UI - change access from private to protected // for testing purposes only, changed from protected to public /** * Answer the editor manager for this window. */ public: EditorManager* GetEditorManager(); /** * Answer the perspective presentation. */ public: PerspectiveHelper* GetPerspectivePresentation(); /** * Answer the editor presentation. */ public: EditorAreaHelper* GetEditorPresentation(); /** * Allow access to the part service for this page ... used internally to * propogate certain types of events to the page part listeners. * @return the part service for this page. */ public: PartService* GetPartService(); /** * See IWorkbenchPage. */ public: QList GetEditors(); public: QList GetDirtyEditors(); public: QList GetDirtyParts(); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer FindEditor(IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: QList FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags); /** * See IWorkbenchPage. */ public: QList GetEditorReferences(); /** * @see IWorkbenchPage */ public: IAdaptable* GetInput(); /** * Returns the page label. This is a combination of the page input and * active perspective. */ public: QString GetLabel(); /** * Returns the perspective. */ public: IPerspectiveDescriptor::Pointer GetPerspective(); /* * (non-Javadoc) Method declared on ISelectionService */ public: ISelection::ConstPointer GetSelection() const; /* * (non-Javadoc) Method declared on ISelectionService */ public: ISelection::ConstPointer GetSelection(const QString& partId); //public: // SelectionEvents& GetSelectionEvents(const QString& partId = ""); /* * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: QList GetViewReferences(); /** * See IWorkbenchPage. */ public: QList GetViews(); /** * Returns all view parts in the specified perspective * * @param persp the perspective * @return an array of view parts * @since 3.1 */ /*package*/ protected: QList GetViews(SmartPointer persp, bool restore); /** * See IWorkbenchPage. */ public: IWorkbenchWindow::Pointer GetWorkbenchWindow(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#hideView(org.blueberry.ui.IViewReference) */ public: void HideView(IViewReference::Pointer ref); /* package */ protected: void RefreshActiveView(); /** * See IPerspective */ public: void HideView(IViewPart::Pointer view); /** * Initialize the page. * * @param w * the parent window * @param layoutID * may be null if restoring from file * @param input * the page input * @param openExtras * whether to process the perspective extras preference */ private: void Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras); /** * Opens the perspectives specified in the PERSPECTIVE_BAR_EXTRAS preference (see bug 84226). */ public: void OpenPerspectiveExtras(); /** * See IWorkbenchPage. */ public: bool IsPartVisible(IWorkbenchPart::Pointer part); /** * See IWorkbenchPage. */ public: bool IsEditorAreaVisible(); /** * Returns whether the view is fast. */ public: bool IsFastView(IViewReference::Pointer ref); /** * Return whether the view is closeable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is closeable. * @since 3.1.1 */ public: bool IsCloseable(IViewReference::Pointer ref); /** * Return whether the view is moveable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is moveable. * @since 3.1.1 */ public: bool IsMoveable(IViewReference::Pointer ref); /** * Returns whether the layout of the active * perspective is fixed. */ public: bool IsFixedLayout(); /** * Return true if the perspective has a dirty editor. */ protected: bool IsSaveNeeded(); /** * This method is called when the page is activated. */ protected: void OnActivate(); /** * This method is called when the page is deactivated. */ protected: void OnDeactivate(); /** * See IWorkbenchPage. */ public: void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags); /** * This is not public API but for use internally. editorState can be null. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * Opens a new editor using the given input and descriptor. (Normally, editors are opened using * an editor ID and an input.) */ public: IEditorPart::Pointer OpenEditorFromDescriptor(IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); /** * @see #openEditor(IEditorInput, String, boolean, int) */ private: IEditorPart::Pointer BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ private: IEditorPart::Pointer BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); /** * Do not call this method. Use busyOpenEditor. * * @see IWorkbenchPage#openEditor(IEditorInput, String, boolean) */ protected: IEditorPart::Pointer BusyOpenEditorBatched(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ private: IEditorPart::Pointer BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); public: void OpenEmptyTab(); protected: void ShowEditor(bool activate, IEditorPart::Pointer editor); /** * See IWorkbenchPage. */ public: bool IsEditorPinned(IEditorPart::Pointer editor); /** * Removes an IPartListener from the part service. */ public: void RemovePartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(const QString& partId, ISelectionListener* listener); /** * This method is called when a part is activated by clicking within it. In * response, the part, the pane, and all of its actions will be activated. * * In the current design this method is invoked by the part pane when the * pane, the part, or any children gain focus. */ public: void RequestActivation(IWorkbenchPart::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ public: void ResetPerspective(); /** * Restore this page from the memento and ensure that the active * perspective is equals the active descriptor otherwise create a new * perspective for that descriptor. If activeDescriptor is null active the * old perspective. */ public: /*IStatus*/bool RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor); /** * See IWorkbenchPage */ public: bool SaveAllEditors(bool confirm); /** * @param confirm * @param addNonPartSources true if saveables from non-part sources should be saved too * @return false if the user cancelled * */ public: bool SaveAllEditors(bool confirm, bool addNonPartSources); /* * Saves the workbench part. */ protected: bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm); /** * Saves an editors in the workbench. If confirm is true * the user is prompted to confirm the command. * * @param confirm * if user confirmation should be sought * @return true if the command succeeded, or false * if the user cancels the command */ public: bool SaveEditor(IEditorPart::Pointer editor, bool confirm); /** * Saves the current perspective. */ public: void SavePerspective(); /** * Saves the perspective. */ public: void SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc); /** * Save the state of the page. */ public: /*IStatus*/bool SaveState(IMemento::Pointer memento); private: QString GetId(IWorkbenchPart::Pointer part); private: QString GetId(IWorkbenchPartReference::Pointer ref); /** * Sets the active part. */ private: void SetActivePart(IWorkbenchPart::Pointer newPart); /** * See IWorkbenchPage. */ public: void SetEditorAreaVisible(bool showEditorArea); /** * Sets the layout of the page. Assumes the new perspective is not null. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ private: void SetPerspective(SmartPointer newPersp); /* * Update visibility state of all views. */ private: void UpdateVisibility(SmartPointer oldPersp, SmartPointer newPersp); /** * Sets the perspective. * * @param desc * identifies the new perspective. */ public: void SetPerspective(IPerspectiveDescriptor::Pointer desc); /** * Restore the toolbar layout for the active perspective. */ protected: void ResetToolBarLayout(); /** * See IWorkbenchPage. */ public: IViewPart::Pointer ShowView(const QString& viewID); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#showView(java.lang.String, * java.lang.String, int) */ public: IViewPart::Pointer ShowView(const QString& viewID, const QString& secondaryID, int mode); /** * @param mode the mode to test * @return whether the mode is recognized * @since 3.0 */ private: bool CertifyMode(int mode); /* * Returns the editors in activation order (oldest first). */ public: QList GetSortedEditors(); /** * @see IWorkbenchPage#getOpenPerspectives() */ public: QList GetOpenPerspectives(); /** * Return all open Perspective objects. * * @return all open Perspective objects * @since 3.1 */ /*package*/ protected: QList > GetOpenInternalPerspectives(); /** * Checks perspectives in the order they were activiated * for the specfied part. The first sorted perspective * that contains the specified part is returned. * * @param part specified part to search for * @return the first sorted perspespective containing the part * @since 3.1 */ /*package*/ protected: SmartPointer GetFirstPerspectiveWithView(IViewPart::Pointer part); /** * Returns the perspectives in activation order (oldest first). */ public: QList GetSortedPerspectives(); /* * Returns the parts in activation order (oldest first). */ public: QList GetSortedParts(); /** * Returns the reference to the given part, or null if it has no reference * (i.e. it is not a top-level part in this workbench page). * * @param part the part * @return the part's reference or null if the given part does not belong * to this workbench page */ public: IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part); // private: class ActivationList { // //List of parts in the activation order (oldest first) // List parts = new ArrayList(); // // /* // * Add/Move the active part to end of the list; // */ // void setActive(IWorkbenchPart part) { // if (parts.size() <= 0) { // return; // } // IWorkbenchPartReference ref = getReference(part); // if (ref != null) { // if (ref == parts.get(parts.size() - 1)) { // return; // } // parts.remove(ref); // parts.add(ref); // } // } // // /* // * Ensures that the given part appears AFTER any other part in the same // * container. // */ // void bringToTop(IWorkbenchPartReference ref) { // ILayoutContainer targetContainer = getContainer(ref); // // int newIndex = lastIndexOfContainer(targetContainer); // // //New index can be -1 if there is no last index // if (newIndex >= 0 && ref == parts.get(newIndex)) // return; // // parts.remove(ref); // if(newIndex >= 0) // parts.add(newIndex, ref); // else // parts.add(ref); // } // // /* // * Returns the last (most recent) index of the given container in the activation list, or returns // * -1 if the given container does not appear in the activation list. // */ // int lastIndexOfContainer(ILayoutContainer container) { // for (int i = parts.size() - 1; i >= 0; i--) { // IWorkbenchPartReference ref = (IWorkbenchPartReference)parts.get(i); // // ILayoutContainer cnt = getContainer(ref); // if (cnt == container) { // return i; // } // } // // return -1; // } // // /* // * Add/Move the active part to end of the list; // */ // void setActive(IWorkbenchPartReference ref) { // setActive(ref.getPart(true)); // } // // /* // * Add the active part to the beginning of the list. // */ // void add(IWorkbenchPartReference ref) { // if (parts.indexOf(ref) >= 0) { // return; // } // // IWorkbenchPart part = ref.getPart(false); // if (part != null) { // PartPane pane = ((PartSite) part.getSite()).getPane(); // if (pane instanceof MultiEditorInnerPane) { // MultiEditorInnerPane innerPane = (MultiEditorInnerPane) pane; // add(innerPane.getParentPane().getPartReference()); // return; // } // } // parts.add(0, ref); // } // // /* // * Return the active part. Filter fast views. // */ // IWorkbenchPart getActive() { // if (parts.isEmpty()) { // return null; // } // return getActive(parts.size() - 1); // } // // /* // * Return the previously active part. Filter fast views. // */ // IWorkbenchPart getPreviouslyActive() { // if (parts.size() < 2) { // return null; // } // return getActive(parts.size() - 2); // } // // private: IWorkbenchPart getActive(int start) { // IWorkbenchPartReference ref = getActiveReference(start, false); // // if (ref == null) { // return null; // } // // return ref.getPart(true); // } // // public: IWorkbenchPartReference getActiveReference(boolean editorsOnly) { // return getActiveReference(parts.size() - 1, editorsOnly); // } // // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly) { // // First look for parts that aren't obscured by the current zoom state // IWorkbenchPartReference nonObscured = getActiveReference(start, editorsOnly, true); // // if (nonObscured != null) { // return nonObscured; // } // // // Now try all the rest of the parts // return getActiveReference(start, editorsOnly, false); // } // // /* // * Find a part in the list starting from the end and filter // * and views from other perspectives. Will filter fast views // * unless 'includeActiveFastViews' is true; // */ // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly, boolean skipPartsObscuredByZoom) { // IWorkbenchPartReference[] views = getViewReferences(); // for (int i = start; i >= 0; i--) { // WorkbenchPartReference ref = (WorkbenchPartReference) parts // .get(i); // // if (editorsOnly && !(ref instanceof IEditorReference)) { // continue; // } // // // Skip parts whose containers have disabled auto-focus // PartPane pane = ref.getPane(); // // if (pane != null) { // if (!pane.allowsAutoFocus()) { // continue; // } // // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } // } // // // Skip fastviews (unless overridden) // if (ref instanceof IViewReference) { // if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { // for (int j = 0; j < views.length; j++) { // if (views[j] == ref) { // return ref; // } // } // } // } else { // return ref; // } // } // return null; // } // // /* // * Retuns the index of the part within the activation list. The higher // * the index, the more recently it was used. // */ // int indexOf(IWorkbenchPart part) { // IWorkbenchPartReference ref = getReference(part); // if (ref == null) { // return -1; // } // return parts.indexOf(ref); // } // // /* // * Returns the index of the part reference within the activation list. // * The higher the index, the more recent it was used. // */ // int indexOf(IWorkbenchPartReference ref) { // return parts.indexOf(ref); // } // // /* // * Remove a part from the list // */ // boolean remove(IWorkbenchPartReference ref) { // return parts.remove(ref); // } // // /* // * Returns the editors in activation order (oldest first). // */ // private: IEditorReference[] getEditors() { // ArrayList editors = new ArrayList(parts.size()); // for (Iterator i = parts.iterator(); i.hasNext();) { // IWorkbenchPartReference part = (IWorkbenchPartReference) i // .next(); // if (part instanceof IEditorReference) { // editors.add(part); // } // } // return (IEditorReference[]) editors // .toArray(new IEditorReference[editors.size()]); // } // // /* // * Return a list with all parts (editors and views). // */ // private: IWorkbenchPartReference[] getParts() { // IWorkbenchPartReference[] views = getViewReferences(); // ArrayList resultList = new ArrayList(parts.size()); // for (Iterator iterator = parts.iterator(); iterator.hasNext();) { // IWorkbenchPartReference ref = (IWorkbenchPartReference) iterator // .next(); // if (ref instanceof IViewReference) { // //Filter views from other perspectives // for (int i = 0; i < views.length; i++) { // if (views[i] == ref) { // resultList.add(ref); // break; // } // } // } else { // resultList.add(ref); // } // } // IWorkbenchPartReference[] result = new IWorkbenchPartReference[resultList // .size()]; // return (IWorkbenchPartReference[]) resultList.toArray(result); // } // // /* // * Returns the topmost editor on the stack, or null if none. // */ // IEditorPart getTopEditor() { // IEditorReference editor = (IEditorReference)getActiveReference(parts.size() - 1, true); // // if (editor == null) { // return null; // } // // return editor.getEditor(true); // } // }; // for dynamic UI protected: void AddPerspective(SmartPointer persp); /** * Find the stack of view references stacked with this view part. * * @param part * the part * @return the stack of references * @since 3.0 */ private: QList GetViewReferenceStack( IViewPart::Pointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getViewStack(org.blueberry.ui.IViewPart) */ public: QList GetViewStack(IViewPart::Pointer part); /** * Allow for programmatically resizing a part. *

    * EXPERIMENTAL *

    *

    * Known limitations: *

      *
    • currently applies only to views
    • *
    • has no effect when view is zoomed
    • *
    */ public: void ResizeView(IViewPart::Pointer part, int width, int height); private: struct ActivationOrderPred : std::binary_function { ActivationOrderPred(ActivationList* partList); ActivationList* activationList; bool operator()(const IViewReference::Pointer o1, const IViewReference::Pointer o2) const; }; // provides sash information for the given pane struct SashInfo { SmartPointer right; SmartPointer left; SmartPointer top; SmartPointer bottom; SmartPointer rightNode; SmartPointer leftNode; SmartPointer topNode; SmartPointer bottomNode; }; void FindSashParts(SmartPointer tree, const PartPane::Sashes& sashes, SashInfo& info); /** * Returns all parts that are owned by this page * * @return */ protected: QList GetAllParts(); /** * Returns all open parts that are owned by this page (that is, all parts * for which a part opened event would have been sent -- these would be * activated parts whose controls have already been created. */ protected: QList GetOpenParts(); /** * Sanity-checks the objects in this page. Throws an Assertation exception * if an object's internal state is invalid. ONLY INTENDED FOR USE IN THE * UI TEST SUITES. */ public: void TestInvariants(); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() */ //public: IExtensionTracker GetExtensionTracker(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ public: QList GetPerspectiveShortcuts(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() */ public: QList GetShowViewShortcuts(); /** * @since 3.1 */ private: void SuggestReset(); public: bool IsPartVisible(IWorkbenchPartReference::Pointer reference); }; } #endif /*BERRYWORKBENCHPAGE_H_*/ 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 5e9f60d5c8..0aad01c756 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp @@ -1,1963 +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(); // } } 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() +QWidget* 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) +QWidget* 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. QRect displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); // 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); // }}); // // } // } 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)) { 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()) { 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()); 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(); + QWidget* 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 5517591391..0a16cf885d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h @@ -1,739 +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 QWidget* 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(); + QWidget* 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); + QWidget* 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 */ 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; + QWidget* emptyWindowContents; 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/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp index 23da392a90..1a8b077ba2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp @@ -1,170 +1,170 @@ /*=================================================================== 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 "berryQtWorkbenchPresentationFactory.h" #include "berryNativeTabFolder.h" #include "berryEmptyTabFolder.h" #include "berryShell.h" #include "berryIMemento.h" #include "internal/util/berryPresentablePartFolder.h" #include "internal/util/berryTabbedStackPresentation.h" #include "internal/berryQtSash.h" #include #include namespace berry { QtWorkbenchPresentationFactory::QtWorkbenchPresentationFactory() {} QtWorkbenchPresentationFactory::QtWorkbenchPresentationFactory( const QtWorkbenchPresentationFactory& /*other*/) : QObject() { } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateEditorPresentation( - void* parent, IStackPresentationSite::Pointer site) + QWidget* parent, IStackPresentationSite::Pointer site) { - NativeTabFolder* folder = new NativeTabFolder(static_cast (parent)); + NativeTabFolder* folder = new NativeTabFolder(parent); // /* // * Set the minimum characters to display, if the preference is something // * other than the default. This is mainly intended for RCP applications // * or for expert users (i.e., via the plug-in customization file). // * // * Bug 32789. // */ // final IPreferenceStore store = PlatformUI.getPreferenceStore(); // if (store // .contains(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS)) { // final int minimumCharacters = store // .getInt(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS); // if (minimumCharacters >= 0) { // folder.setMinimumCharacters(minimumCharacters); // } // } PresentablePartFolder* partFolder = new PresentablePartFolder(folder); StackPresentation::Pointer result(new TabbedStackPresentation(site, partFolder)); //, new StandardEditorSystemMenu(site)); // DefaultThemeListener themeListener = // new DefaultThemeListener(folder, result.getTheme()); // result.getTheme().addListener(themeListener); // // new DefaultMultiTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_MULTIPLE_EDITOR_TABS, folder); // // new DefaultSimpleTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, folder); return result; } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateViewPresentation( - void* parent, IStackPresentationSite::Pointer site) + QWidget* parent, IStackPresentationSite::Pointer site) { NativeTabFolder* folder = new NativeTabFolder(static_cast (parent)); // final IPreferenceStore store = PlatformUI.getPreferenceStore(); // final int minimumCharacters = store // .getInt(IWorkbenchPreferenceConstants.VIEW_MINIMUM_CHARACTERS); // if (minimumCharacters >= 0) { // folder.setMinimumCharacters(minimumCharacters); // } PresentablePartFolder* partFolder = new PresentablePartFolder(folder); //folder->SetUnselectedCloseVisible(false); //folder->SetUnselectedImageVisible(true); StackPresentation::Pointer result(new TabbedStackPresentation(site, partFolder)); //, new StandardViewSystemMenu(site)); // DefaultThemeListener themeListener = // new DefaultThemeListener(folder, result.getTheme()); // result.getTheme().addListener(themeListener); // // new DefaultSimpleTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, folder); return result; } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateStandaloneViewPresentation( - void* parent, IStackPresentationSite::Pointer site, bool showTitle) + QWidget* parent, IStackPresentationSite::Pointer site, bool showTitle) { if (showTitle) { return this->CreateViewPresentation(parent, site); } EmptyTabFolder* folder = new EmptyTabFolder(static_cast (parent), true); StackPresentation::Pointer presentation(new TabbedStackPresentation(site, folder)); //, new StandardViewSystemMenu(site)); return presentation; } QString QtWorkbenchPresentationFactory::GetId() { return "berryQtWorkbenchPresentationFactory"; } -void* QtWorkbenchPresentationFactory::CreateSash(void* parent, int style) +QWidget* QtWorkbenchPresentationFactory::CreateSash(QWidget* parent, int style) { Qt::Orientation orientation = style & SASHORIENTATION_HORIZONTAL ? Qt::Horizontal : Qt::Vertical; QWidget* sash = new QtSash(orientation, static_cast (parent)); sash->setObjectName("Sash widget"); if (orientation == Qt::Horizontal) sash->setFixedHeight(this->GetSashSize(style)); else sash->setFixedWidth(this->GetSashSize(style)); return sash; } int QtWorkbenchPresentationFactory::GetSashSize(int /*style*/) { return 3; } void QtWorkbenchPresentationFactory::UpdateTheme() { QWidgetList topLevels = QApplication::topLevelWidgets(); QListIterator topIt(topLevels); while (topIt.hasNext()) { QWidget* topWidget = topIt.next(); QList folders = topWidget->findChildren (); QListIterator i(folders); while (i.hasNext()) { i.next()->UpdateColors(); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h index bc29dd30db..ff96c4bf2f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h @@ -1,87 +1,87 @@ /*=================================================================== 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 BERRYQTWORKBENCHPRESENTATIONFACTORY_H_ #define BERRYQTWORKBENCHPRESENTATIONFACTORY_H_ #include namespace berry { /** * The default presentation factory for the Workbench. * */ class QtWorkbenchPresentationFactory: public QObject, public IPresentationFactory { Q_OBJECT Q_INTERFACES(berry::IPresentationFactory) // // don't reset these dynamically, so just keep the information static. // // see bug: // // 75422 [Presentations] Switching presentation to R21 switches immediately, // // but only partially // private static int editorTabPosition = PlatformUI.getPreferenceStore() // .getInt(IWorkbenchPreferenceConstants.EDITOR_TAB_POSITION); // private static int viewTabPosition = PlatformUI.getPreferenceStore() // .getInt(IWorkbenchPreferenceConstants.VIEW_TAB_POSITION); public: QtWorkbenchPresentationFactory(); QtWorkbenchPresentationFactory(const QtWorkbenchPresentationFactory& other); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.AbstractPresentationFactory#createEditorPresentation(org.blueberry.swt.widgets.Composite, * org.blueberry.ui.presentations.IStackPresentationSite) */ - StackPresentation::Pointer CreateEditorPresentation(void* parent, + StackPresentation::Pointer CreateEditorPresentation(QWidget* parent, IStackPresentationSite::Pointer site); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.AbstractPresentationFactory#createViewPresentation(org.blueberry.swt.widgets.Composite, * org.blueberry.ui.presentations.IStackPresentationSite) */ - StackPresentation::Pointer CreateViewPresentation(void* parent, + StackPresentation::Pointer CreateViewPresentation(QWidget* parent, IStackPresentationSite::Pointer site); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.AbstractPresentationFactory#createStandaloneViewPresentation(org.blueberry.swt.widgets.Composite, * org.blueberry.ui.presentations.IStackPresentationSite, boolean) */ - StackPresentation::Pointer CreateStandaloneViewPresentation(void* parent, + StackPresentation::Pointer CreateStandaloneViewPresentation(QWidget* parent, IStackPresentationSite::Pointer site, bool showTitle); QString GetId(); - void* CreateSash(void* parent, int style); + QWidget* CreateSash(QWidget* parent, int style); int GetSashSize(int style); void UpdateTheme(); }; } #endif /* BERRYQTWORKBENCHPRESENTATIONFACTORY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp index 5a84c743e7..7fb5a807f5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.cpp @@ -1,141 +1,141 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEditorIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { EditorIntroAdapterPart::EditorIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &EditorIntroAdapterPart::PropertyChange)) { } void EditorIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } -void EditorIntroAdapterPart::CreatePartControl(void* parent) +void EditorIntroAdapterPart::CreatePartControl(QWidget* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } EditorIntroAdapterPart::~EditorIntroAdapterPart() { //setBarVisibility(true); if(introPart) { introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } } QIcon EditorIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString EditorIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? EditorPart::GetPartName() : introPart->GetPartName(); } void EditorIntroAdapterPart::Init(IEditorSite::Pointer site, IEditorInput::Pointer input) { Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager()->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, IMemento::Pointer(0)); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro editor proxy.", e); } this->SetSite(site); this->SetInput(input); } void EditorIntroAdapterPart::DoSave(/*IProgressMonitor monitor*/) { } void EditorIntroAdapterPart::DoSaveAs() { } bool EditorIntroAdapterPart::IsDirty() const { return false; } bool EditorIntroAdapterPart::IsSaveAsAllowed() const { return false; } void EditorIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void EditorIntroAdapterPart::SetFocus() { introPart->SetFocus(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h index ac005a0adc..53e4a03a95 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryEditorIntroAdapterPart.h @@ -1,159 +1,159 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEDITORINTROADAPTERPART_H_ #define BERRYEDITORINTROADAPTERPART_H_ #include #include #include namespace berry { /** * Simple editor that will wrap an IIntroPart. */ class EditorIntroAdapterPart: public EditorPart { Q_OBJECT private: IIntroPart::Pointer introPart; IIntroSite::Pointer introSite; QScopedPointer propChangeListener; friend struct PropertyChangeIntAdapter ; void PropertyChange(const Object::Pointer& source, int propId); // bool handleZoomEvents = true; // /** // * Adds a listener that toggles standby state if the view pane is zoomed. // */ // void AddPaneListener() { // IWorkbenchPartSite site = getSite(); // if (site instanceof PartSite) { // final WorkbenchPartReference ref = ((WorkbenchPartReference)((PartSite) site).getPartReference()); // ref.addInternalPropertyListener( // new IPropertyListener() { // public void propertyChanged(Object source, int propId) { // if (handleZoomEvents) { // if (propId == WorkbenchPartReference.INTERNAL_PROPERTY_ZOOMED) { // setStandby(!ref.getPane().isZoomed()); // } // } // } // }); // } // } // /** // * Sets whether the CoolBar/PerspectiveBar should be visible. // * // * @param visible whether the CoolBar/PerspectiveBar should be visible // */ // void SetBarVisibility(bool visible) { // WorkbenchWindow window = (WorkbenchWindow) getSite() // .getWorkbenchWindow(); // // final boolean layout = (visible != window.getCoolBarVisible()) // || (visible != window.getPerspectiveBarVisible()); // don't layout unless things have actually changed // if (visible) { // window.setCoolBarVisible(true); // window.setPerspectiveBarVisible(true); // } else { // window.setCoolBarVisible(false); // window.setPerspectiveBarVisible(false); // } // // if (layout) { // window.getShell().layout(); // } // } public: EditorIntroAdapterPart(); /** * Forces the standby state of the intro part. * * @param standby update the standby state */ void SetStandby(bool standby); // /** // * Toggles handling of zoom events. // * // * @param handle whether to handle zoom events // */ // void SetHandleZoomEvents(boolean handle) { // handleZoomEvents = handle; // } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ ~EditorIntroAdapterPart(); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#getTitleImage() */ QIcon GetTitleImage() const; /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#GetPartName() */ QString GetPartName() const; void Init(IEditorSite::Pointer site, IEditorInput::Pointer input); void DoSave(/*IProgressMonitor monitor*/); void DoSaveAs(); bool IsDirty() const; bool IsSaveAsAllowed() const; /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento) */ void SaveState(IMemento::Pointer memento); }; } #endif /* BERRYEDITORINTROADAPTERPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp index feba83a59f..f58e68715c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp @@ -1,121 +1,121 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" #include "internal/berryWorkbench.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { ViewIntroAdapterPart::ViewIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &ViewIntroAdapterPart::PropertyChange)) { } void ViewIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } -void ViewIntroAdapterPart::CreatePartControl(void* parent) +void ViewIntroAdapterPart::CreatePartControl(QWidget* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } ViewIntroAdapterPart::~ViewIntroAdapterPart() { //setBarVisibility(true); introPart->RemovePropertyListener(propChangeListener.data()); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } QIcon ViewIntroAdapterPart::GetTitleImage() const { return introPart->GetTitleImage(); } QString ViewIntroAdapterPart::GetPartName() const { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? ViewPart::GetPartName() : introPart->GetPartName(); } void ViewIntroAdapterPart::Init(IViewSite::Pointer site, IMemento::Pointer memento) throw (PartInitException) { ViewPart::Init(site); Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager() ->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener.data()); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, memento); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro view proxy.", e); } } void ViewIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/, int propId) { FirePropertyChange(propId); } void ViewIntroAdapterPart::SetFocus() { introPart->SetFocus(); } void ViewIntroAdapterPart::SaveState(IMemento::Pointer memento) { introPart->SaveState(memento); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h index 26420ca316..407e025a06 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.h @@ -1,155 +1,155 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYVIEWINTROADAPTERPART_H_ #define BERRYVIEWINTROADAPTERPART_H_ #include #include #include namespace berry { /** * Simple view that will wrap an IIntroPart. * * @since 3.0 */ class ViewIntroAdapterPart: public ViewPart { private: IIntroPart::Pointer introPart; IIntroSite::Pointer introSite; QScopedPointer propChangeListener; friend struct PropertyChangeIntAdapter ; void PropertyChange(const Object::Pointer& source, int propId); // bool handleZoomEvents = true; // /** // * Adds a listener that toggles standby state if the view pane is zoomed. // */ // void AddPaneListener() { // IWorkbenchPartSite site = getSite(); // if (site instanceof PartSite) { // final WorkbenchPartReference ref = ((WorkbenchPartReference)((PartSite) site).getPartReference()); // ref.addInternalPropertyListener( // new IPropertyListener() { // public void propertyChanged(Object source, int propId) { // if (handleZoomEvents) { // if (propId == WorkbenchPartReference.INTERNAL_PROPERTY_ZOOMED) { // setStandby(!ref.getPane().isZoomed()); // } // } // } // }); // } // } // /** // * Sets whether the CoolBar/PerspectiveBar should be visible. // * // * @param visible whether the CoolBar/PerspectiveBar should be visible // */ // void SetBarVisibility(bool visible) { // WorkbenchWindow window = (WorkbenchWindow) getSite() // .getWorkbenchWindow(); // // final boolean layout = (visible != window.getCoolBarVisible()) // || (visible != window.getPerspectiveBarVisible()); // don't layout unless things have actually changed // if (visible) { // window.setCoolBarVisible(true); // window.setPerspectiveBarVisible(true); // } else { // window.setCoolBarVisible(false); // window.setPerspectiveBarVisible(false); // } // // if (layout) { // window.getShell().layout(); // } // } public: ViewIntroAdapterPart(); /** * Forces the standby state of the intro part. * * @param standby update the standby state */ void SetStandby(bool standby); // /** // * Toggles handling of zoom events. // * // * @param handle whether to handle zoom events // */ // void SetHandleZoomEvents(boolean handle) { // handleZoomEvents = handle; // } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ ~ViewIntroAdapterPart(); /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#getTitleImage() */ QIcon GetTitleImage() const; /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#GetPartName() */ QString GetPartName() const; /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#init(org.eclipse.ui.IViewSite, org.eclipse.ui.IMemento) */ void Init(IViewSite::Pointer site, IMemento::Pointer memento = IMemento::Pointer(0)) throw (PartInitException); /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento) */ void SaveState(IMemento::Pointer memento); }; } #endif /* BERRYVIEWINTROADAPTERPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryTabbedStackPresentation.cpp index b0ec449337..417e960990 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,499 +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; 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 QRect& bounds) { folder->SetBounds(bounds); } QSize TabbedStackPresentation::ComputeMinimumSize() { 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() +QWidget* 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 QPoint& location) +StackDropResult::Pointer TabbedStackPresentation::DragOver(QWidget* currentControl, const QPoint& location) { QWidget* currentWidget = static_cast(currentControl); return dragBehavior->DragOver(currentWidget, location, dragStart); } -QList TabbedStackPresentation::GetTabList( +QList TabbedStackPresentation::GetTabList( IPresentablePart::Pointer part) { - QList list; + 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 359ff6f791..9f64f417a8 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.QRect) */ void SetBounds(const QRect& bounds); /* (non-Javadoc) * @see org.blueberry.ui.presentations.StackPresentation#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(); + QWidget* 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&) + * @see org.blueberry.ui.presentations.StackPresentation#DragOver(QWidget*, const Point&) */ - StackDropResult::Pointer DragOver(void* currentControl, const QPoint& location); + StackDropResult::Pointer DragOver(QWidget* 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); + 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 0359d32cc9..c0a183722c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentablePart.h @@ -1,268 +1,270 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPRESENTABLEPART_H_ #define BERRYIPRESENTABLEPART_H_ #include #include "berryISizeProvider.h" #include "berryIPropertyChangeListener.h" +class QToolBar; + 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 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; + virtual QToolBar* 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; + virtual QWidget* 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/berryIPresentationFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentationFactory.h index 82467ebc99..37b4a50520 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentationFactory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/presentations/berryIPresentationFactory.h @@ -1,185 +1,185 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPRESENTATIONFACTORY_H_ #define BERRYIPRESENTATIONFACTORY_H_ #include #include "berryStackPresentation.h" #include namespace berry { /** * This is a factory for presentation objects that control the appearance of * editors, views and other components in the workbench. * * @since 3.0 */ class BERRY_UI_QT IPresentationFactory { public: virtual ~IPresentationFactory(); /** * Bit value for the createSash method's 'style' parameter. * @since 3.4 */ static int SASHTYPE_NORMAL; // = 0; /** * Bit value for the createSash method's 'style' parameter. * @since 3.4 */ static int SASHTYPE_FLOATING; // = 1<<1; /** * Bit value for the createSash method's 'style' parameter. * @since 3.4 */ static int SASHORIENTATION_HORIZONTAL; // = SWT.HORIZONTAL; // 1<<8 /** * Bit value for the createSash method's 'style' parameter. * @since 3.4 */ static int SASHORIENTATION_VERTICAL; // = SWT.VERTICAL; // 1<<9 /** * Creates an editor presentation for presenting editors. *

    * The presentation creates its controls under the given parent composite. *

    * * @param parent * the parent composite to use for the presentation's controls * @param site * the site used for communication between the presentation and * the workbench * @return a newly created part presentation */ virtual StackPresentation::Pointer CreateEditorPresentation( - void* parent, IStackPresentationSite::Pointer site) = 0; + QWidget* parent, IStackPresentationSite::Pointer site) = 0; /** * Creates a stack presentation for presenting regular docked views. *

    * The presentation creates its controls under the given parent composite. *

    * * @param parent * the parent composite to use for the presentation's controls * @param site * the site used for communication between the presentation and * the workbench * @return a newly created part presentation */ - virtual StackPresentation::Pointer CreateViewPresentation(void* parent, + virtual StackPresentation::Pointer CreateViewPresentation(QWidget* parent, IStackPresentationSite::Pointer site) = 0; /** * Creates a standalone stack presentation for presenting a standalone view. * A standalone view cannot be docked together with other views. The title * of a standalone view may be hidden. *

    * The presentation creates its controls under the given parent composite. *

    * * @param parent * the parent composite to use for the presentation's controls * @param site * the site used for communication between the presentation and * the workbench * @param showTitle * true to show the title for the view, * false to hide it * @return a newly created part presentation */ virtual StackPresentation::Pointer CreateStandaloneViewPresentation( - void* parent, IStackPresentationSite::Pointer site, bool showTitle) = 0; + QWidget* parent, IStackPresentationSite::Pointer site, bool showTitle) = 0; /** * Creates the status line manager for the window. * Subclasses may override. * * @return the window's status line manager */ // public IStatusLineManager createStatusLineManager() { // return new StatusLineManager(); // } /** * Creates the control for the window's status line. * Subclasses may override. * * @param statusLine the window's status line manager * @param parent the parent composite * @return the window's status line control */ // public Control createStatusLineControl(IStatusLineManager statusLine, // Composite parent) { // return ((StatusLineManager) statusLine).createControl(parent, SWT.NONE); // } /** * Returns a globally unique identifier for this type of presentation factory. This is used * to ensure that one presentation is not restored from mementos saved by a different * presentation. * * @return a globally unique identifier for this type of presentation factory. */ virtual QString GetId() = 0; /** * Creates the Sash control that is used to separate view and editor parts. * * @param parent the parent composite * @param style A bit set giving both the 'type' of the desired sash and * its orientation (i.e. one 'SASHTYPE' value and one "SASHORIENTATION" value). * @return the sash control * @since 3.4 */ - virtual void* CreateSash(void* parent, int style) = 0; + virtual QWidget* CreateSash(QWidget* parent, int style) = 0; // { // int orientation = style & (SASHORIENTATION_HORIZONTAL // | SASHORIENTATION_VERTICAL); // Sash sash = new Sash(parent, orientation | SWT.SMOOTH); // return sash; // } /** * Returns the size of the Sash control that is used to separate view and editor parts. * * @param style A bit set giving both the 'type' of the desired sash and * its orientation. * @return the sash size * @since 3.4 */ virtual int GetSashSize(int style) = 0; /** * Applies changes of the current theme to the user interface. */ virtual void UpdateTheme() = 0; }; } Q_DECLARE_INTERFACE(berry::IPresentationFactory, "org.blueberry.ui.IPresentationFactory") #endif /* BERRYABSTRACTPRESENTATIONFACTORY_H_ */ 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 d50856d686..c326a04d25 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) 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 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 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; + virtual QWidget* 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 QPoint& location) = 0; + virtual StackDropResult::Pointer DragOver(QWidget* 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; + virtual QList GetTabList(IPresentablePart::Pointer part) = 0; }; } #endif /* BERRYSTACKPRESENTATION_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 197b1c2051..b6b6bf170f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h @@ -1,210 +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 "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; + virtual void AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) = 0; + virtual void RemoveSelectionListener(QWidget* 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; + virtual void AddControlListener(QWidget* 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 void RemoveControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener) = 0; - virtual bool GetEnabled(void* widget) = 0; - virtual void SetEnabled(void* widget, bool enabled) = 0; + virtual bool GetEnabled(QWidget* widget) = 0; + virtual void SetEnabled(QWidget* widget, bool enabled) = 0; - virtual void SetBounds(void* widget, const QRect& bounds) = 0; - virtual QRect GetBounds(void* widget) = 0; + virtual void SetBounds(QWidget* widget, const QRect& bounds) = 0; + virtual QRect GetBounds(QWidget* widget) = 0; - virtual void SetVisible(void* widget, bool visible) = 0; - virtual bool GetVisible(void* widget) = 0; - virtual bool IsVisible(void* widget) = 0; + virtual void SetVisible(QWidget* widget, bool visible) = 0; + virtual bool GetVisible(QWidget* widget) = 0; + virtual bool IsVisible(QWidget* widget) = 0; - virtual QRect GetClientArea(void* widget) = 0; + virtual QRect GetClientArea(QWidget* widget) = 0; - virtual void* GetParent(void* widget) = 0; - virtual bool SetParent(void* widget, void* parent) = 0; + virtual QWidget* GetParent(QWidget* widget) = 0; + virtual bool SetParent(QWidget* widget, QWidget* 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 void SetData(QWidget* widget, const QString& id, Object::Pointer data) = 0; + virtual Object::Pointer GetData(QWidget* widget, const QString& id) = 0; virtual QPoint GetCursorLocation() = 0; - virtual void* GetCursorControl() = 0; - virtual void* FindControl(const QList& shells, const QPoint& location) = 0; + virtual QWidget* GetCursorControl() = 0; + virtual QWidget* 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; + virtual bool IsChild(QWidget* potentialParent, QWidget* 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 QWidget* GetFocusControl() = 0; - virtual bool IsReparentable(void* widget) = 0; + virtual bool IsReparentable(QWidget* widget) = 0; - virtual void MoveAbove(void* widgetToMove, void* widget) = 0; - virtual void MoveBelow(void* widgetToMove, void* widget) = 0; + virtual void MoveAbove(QWidget* widgetToMove, QWidget* widget) = 0; + virtual void MoveBelow(QWidget* widgetToMove, QWidget* widget) = 0; - virtual void Dispose(void* widget) = 0; + virtual void Dispose(QWidget* 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 QWidget* CreateComposite(QWidget* parent) = 0; virtual QList GetShells() = 0; - virtual Shell::Pointer GetShell(void* widget) = 0; + virtual Shell::Pointer GetShell(QWidget* 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(QWidget*, 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 QRect GetScreenSize(int i = -1) = 0; virtual QRect GetAvailableScreenSize(int i = -1) = 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 QRect ToControl(void* coordinateSystem, + virtual QRect ToControl(QWidget* 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 QPoint ToControl(void* coordinateSystem, + virtual QPoint ToControl(QWidget* 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 QRect ToDisplay(void* coordinateSystem, + virtual QRect ToDisplay(QWidget* 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 QPoint ToDisplay(void* coordinateSystem, + virtual QPoint ToDisplay(QWidget* 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/berryWorkbenchPageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryWorkbenchPageTweaklet.h index 94314d6781..d81c887a92 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryWorkbenchPageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/tweaklets/berryWorkbenchPageTweaklet.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 BERRYWORKBENCHPAGETWEAKLET_H_ #define BERRYWORKBENCHPAGETWEAKLET_H_ #include "internal/berryTweaklets.h" #include "berryIWorkbenchPage.h" namespace berry { struct BERRY_UI_QT WorkbenchPageTweaklet { static Tweaklets::TweakKey KEY; - virtual void* CreateClientComposite(void* pageControl) = 0; - virtual void* CreatePaneControl(void* parent) = 0; + virtual QWidget* CreateClientComposite(QWidget* pageControl) = 0; + virtual QWidget* CreatePaneControl(QWidget* parent) = 0; - virtual Object::Pointer CreateStatusPart(void* parent, const QString& title, const QString& msg) = 0; + virtual Object::Pointer CreateStatusPart(QWidget* parent, const QString& title, const QString& msg) = 0; virtual IEditorPart::Pointer CreateErrorEditorPart(const QString& partName, const QString& msg) = 0; }; } Q_DECLARE_INTERFACE(berry::WorkbenchPageTweaklet, "org.blueberry.WorkbenchPageTweaklet") #endif /* BERRYWORKBENCHPAGETWEAKLET_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp index 5212018bab..ea161dc34d 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp @@ -1,379 +1,379 @@ /*=================================================================== 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 "QmitkFunctionality.h" #include "internal/QmitkFunctionalityUtil.h" #include "internal/QmitkCommonLegacyActivator.h" // other includes #include // mitk Includes #include #include // berry Includes #include #include #include #include // Qmitk Includes #include // Qt Includes #include #include #include #include QmitkFunctionality::QmitkFunctionality() : m_Parent(0) , m_Active(false) , m_Visible(false) , m_SelectionProvider(0) , m_DataStorageServiceTracker(QmitkCommonLegacyActivator::GetContext()) , m_HandlesMultipleDataStorages(false) , m_InDataStorageChanged(false) { m_DataStorageServiceTracker.open(); } void QmitkFunctionality::SetHandleMultipleDataStorages(bool multiple) { m_HandlesMultipleDataStorages = multiple; } bool QmitkFunctionality::HandlesMultipleDataStorages() const { return m_HandlesMultipleDataStorages; } mitk::DataStorage::Pointer QmitkFunctionality::GetDataStorage() const { mitk::IDataStorageService* service = m_DataStorageServiceTracker.getService(); if (service != 0) { if(m_HandlesMultipleDataStorages) return service->GetActiveDataStorage()->GetDataStorage(); else return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } mitk::DataStorage::Pointer QmitkFunctionality::GetDefaultDataStorage() const { mitk::IDataStorageService* service = m_DataStorageServiceTracker.getService(); if (service != 0) { return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } mitk::IDataStorageReference::Pointer QmitkFunctionality::GetDataStorageReference() const { mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); if (dsService != 0) { return dsService->GetDataStorage(); } return mitk::IDataStorageReference::Pointer(0); } -void QmitkFunctionality::CreatePartControl(void* parent) +void QmitkFunctionality::CreatePartControl(QWidget* parent) { // scrollArea QScrollArea* scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); QVBoxLayout* parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkFunctionality::AfterCreateQtPartControl() { // REGISTER DATASTORAGE LISTENER this->GetDefaultDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS m_BlueBerrySelectionListener.reset(new berry::SelectionChangedAdapter( this, &QmitkFunctionality::BlueBerrySelectionChanged) ); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener( /*"org.mitk.views.datamanager",*/ m_BlueBerrySelectionListener.data()); // REGISTER A SELECTION PROVIDER QmitkFunctionalitySelectionProvider::Pointer _SelectionProvider( new QmitkFunctionalitySelectionProvider(this)); m_SelectionProvider = _SelectionProvider.GetPointer(); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(m_SelectionProvider)); // EMULATE INITIAL SELECTION EVENTS // by default a a multi widget is always available this->StdMultiWidgetAvailable(*this->GetActiveStdMultiWidget()); // send datamanager selection this->OnSelectionChanged(this->GetDataManagerSelection()); // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } void QmitkFunctionality::ClosePart() { } void QmitkFunctionality::ClosePartProxy() { this->GetDefaultDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy) ); this->GetDefaultDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(NULL)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(m_BlueBerrySelectionListener.data()); } this->ClosePart(); } QmitkFunctionality::~QmitkFunctionality() { this->Register(); this->ClosePartProxy(); this->UnRegister(false); m_DataStorageServiceTracker.close(); } void QmitkFunctionality::OnPreferencesChanged( const berry::IBerryPreferences* ) { } void QmitkFunctionality::BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart->GetSite()->GetId() != "org.mitk.views.datamanager") return; mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); this->OnSelectionChanged(this->DataNodeSelectionToVector(_DataNodeSelection)); } bool QmitkFunctionality::IsVisible() const { return m_Visible; } void QmitkFunctionality::SetFocus() { } void QmitkFunctionality::Activated() { } void QmitkFunctionality::Deactivated() { } void QmitkFunctionality::StdMultiWidgetAvailable( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::StdMultiWidgetNotAvailable() { } void QmitkFunctionality::DataStorageChanged() { } QmitkStdMultiWidget* QmitkFunctionality::GetActiveStdMultiWidget( bool reCreateWidget ) { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (reCreateWidget || editor.Cast().IsNull() ) { mitk::DataStorageEditorInput::Pointer editorInput( new mitk::DataStorageEditorInput( this->GetDataStorageReference() )); // open a new multi-widget editor, but do not give it the focus berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false, berry::IWorkbenchPage::MATCH_ID); activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } else if (editor.Cast().IsNotNull()) { activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } return activeStdMultiWidget; } void QmitkFunctionality::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkFunctionality::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkFunctionality::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkFunctionality::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkFunctionality::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkFunctionality::GetPreferences() const { berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const QString id = "/" + (const_cast(this))->GetViewSite()->GetId(); return prefService != nullptr ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); } void QmitkFunctionality::Visible() { } void QmitkFunctionality::Hidden() { } bool QmitkFunctionality::IsExclusiveFunctionality() const { return true; } void QmitkFunctionality::SetVisible( bool visible ) { m_Visible = visible; } void QmitkFunctionality::SetActivated( bool activated ) { m_Active = activated; } bool QmitkFunctionality::IsActivated() const { return m_Active; } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h index de2fbda10b..cd75b49c53 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h @@ -1,406 +1,406 @@ /*=================================================================== 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. ===================================================================*/ #ifndef QMITKFUNCTIONALITY_H_ #define QMITKFUNCTIONALITY_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include #include #include // CTK Includes #include //# forward declarations namespace mitk { class DataNode; struct IDataStorageService; } namespace berry { struct IBerryPreferences; } class QmitkFunctionalitySelectionProvider; /// /// \ingroup org_mitk_gui_qt_common_legacy /// /// \class QmitkFunctionality /// /// \brief The base class of all MITK related blueberry views (~ in the old version of MITK, this was called "Functionality") /// /// QmitkFunctionality provides several convenience methods that eases the introduction of a new view: /// ///
      ///
    1. Access to the DataStorage (~ the shared data repository) ///
    2. Access to the StdMultiWidget (the 2x2 RenderWindow arrangement) ///
    3. Access to and update notification for the functionality/view preferences ///
    4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService ///
    5. Methods to send DataNode selections through the SelectionService ///
    6. Some events for unproblematic inter-View communication (e.g. when to add/remove interactors) ///
    7. Some minor important convenience methods (like changing the mouse cursor/exception handling) ///
    /// /// Please use the Activated/Deactivated method to add/remove interactors, disabling multiwidget crosshair or anything which may /// "affect" other functionalities. For further reading please have a look at QmitkFunctionality::IsExclusiveFunctionality(). /// class MITK_QT_COMMON_LEGACY QmitkFunctionality : public berry::QtViewPart { //# public virtual methods which can be overwritten public: /// /// Creates smartpointer typedefs /// berryObjectMacro(QmitkFunctionality); /// /// Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) /// \see berry::QtViewPart::CreateQtPartControl(QWidget*) /// QmitkFunctionality(); /// /// Disconnects all standard event listeners /// virtual ~QmitkFunctionality(); /// /// Called, when the WorkbenchPart gets closed /// by the user directly or by closing the whole /// app (e.g. for removing event listeners) /// virtual void ClosePart(); /// /// Called when the selection in the workbench changed /// virtual void OnSelectionChanged(std::vector /*nodes*/); /// /// Called when the preferences object of this view changed. /// \see GetPreferences() /// virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /// /// Make this view manage multiple DataStorage. If set to true GetDataStorage() /// will return the currently active DataStorage (and not the default one). /// \see GetDataStorage() /// void SetHandleMultipleDataStorages(bool multiple); /// /// \return true if this view handles multiple DataStorages, false otherwise /// bool HandlesMultipleDataStorages() const; /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available anymore. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetNotAvailable(); /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Activated(); /// /// \return true if this view is currently activated, false otherwise /// bool IsActivated() const; /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Deactivated(); /// /// Some functionalities need to add special interactors, removes the crosshair from the stdmultiwidget, etc. /// In this case the functionality has to tidy up when changing to another functionality /// which also wants to change the "default configuration". In the old Qt3-based /// version of MITK, two functionalities could never be opened at the same time so that the /// methods Activated() and Deactivated() were the right place for the functionalitites to /// add/remove their interactors, etc. This is still true for the new MITK Workbench, /// but as there can be several functionalities visible at the same time, the behaviour concerning /// when Activated() and Deactivated() are called has changed: /// /// 1. Activated() and Deactivated() are only called if IsExclusiveFunctionality() returns true /// /// 2. If only one standalone functionality is or becomes visible, Activated() will be called on that functionality /// /// 3. If two or more standalone functionalities are visible, /// Activated() will be called on the functionality that receives focus, Deactivated() will be called /// on the one that looses focus, gets hidden or closed /// /// /// As a consequence of 1. if you overwrite IsExclusiveFunctionality() and let it return false, you /// signalize the MITK Workbench that this functionality does nothing to the "default configuration" /// and can easily be visible while other functionalities are also visible. /// /// By default the method returns true. /// /// \return true if this functionality is meant to work as a standalone view, false otherwise /// virtual bool IsExclusiveFunctionality() const; /// /// Informs other parts of the workbench that node is selected via the blueberry selection service. /// void FireNodeSelected(mitk::DataNode* node); /// /// Informs other parts of the workbench that the nodes are selected via the blueberry selection service. /// void FireNodesSelected(std::vector nodes); /// /// Called when this functionality becomes visible ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Visible(); /// /// \return true if this view is currently visible, false otherwise /// bool IsVisible() const; /// /// Called when this functionality is hidden ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Hidden(); //# protected virtual methods which can be overwritten protected: /// /// Called when a DataStorage Add event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeAdded(const mitk::DataNode* node); /// /// Called when a DataStorage Changed event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeChanged(const mitk::DataNode* /*node*/); /// /// Called when a DataStorage Remove event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeRemoved(const mitk::DataNode* node); /// /// Called when a DataStorage add *or* remove *or* change event was thrown. May be reimplemented /// by deriving classes. /// virtual void DataStorageChanged(); /// /// \return the selection of the currently active part of the workbench or an empty vector /// if nothing is selected /// std::vector GetCurrentSelection() const; /// /// Returns the current selection made in the datamanager bundle or an empty vector /// if nothing`s selected or if the bundle does not exist /// std::vector GetDataManagerSelection() const; /// /// Returns the Preferences object for this Functionality. /// Important: When refering to this preferences, e.g. in a PreferencePage: The ID /// for this preferences object is "/", e.g. "/org.mitk.views.datamanager" /// berry::IPreferences::Pointer GetPreferences() const; /// /// Returns the default or the currently active DataStorage if m_HandlesMultipleDataStorages /// is set to true /// \see SetHandleMultipleDataStorages(bool) /// \see HandlesMultipleDataStorages() /// mitk::DataStorage::Pointer GetDataStorage() const; /// /// \return always returns the default DataStorage /// mitk::DataStorage::Pointer GetDefaultDataStorage() const; mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /// /// Returns the default and active StdMultiWidget. /// \param reCreateWidget a boolean flag to en-/disable the attept to re-create the StdWidget /// If there is not StdMultiWidget yet a new one is /// created in this method when called with default parameter! /// QmitkStdMultiWidget* GetActiveStdMultiWidget( bool reCreateWidget = true); /// /// Outputs an error message to the console and displays a message box containing /// the exception description. /// \param e the exception which should be handled /// \param showDialog controls, whether additionally a message box should be /// displayed to inform the user that something went wrong /// void HandleException( std::exception& e, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Calls HandleException ( std::exception&, QWidget*, bool ) internally /// \see HandleException ( std::exception&, QWidget*, bool ) /// void HandleException( const char* str, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Convenient method to set and reset a wait cursor ("hourglass") /// void WaitCursorOn(); /// /// Convenient method to restore the standard cursor /// void WaitCursorOff(); /// /// Convenient method to set and reset a busy cursor /// void BusyCursorOn(); /// /// Convenient method to restore the standard cursor /// void BusyCursorOff(); /// /// Convenient method to restore the standard cursor /// void RestoreOverrideCursor(); //# other public methods which should not be overwritten public: /// /// Creates a scroll area for this view and calls CreateQtPartControl then /// - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); /// /// Called when this view receives the focus. Same as Activated() /// \see Activated() /// void SetFocus(); /// /// Called when a DataStorage Add Event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeAdded afterwards. /// \see m_InDataStorageChanged /// void NodeAddedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage remove event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeRemoved afterwards. /// \see m_InDataStorageChanged /// void NodeRemovedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage changed event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeChanged afterwards. /// \see m_InDataStorageChanged /// void NodeChangedProxy(const mitk::DataNode* node); /// /// Toggles the visible flag m_Visible /// void SetVisible(bool visible); /// /// Toggles the activated flag m_Activated /// void SetActivated(bool activated); /// /// Called, when the WorkbenchPart gets closed for removing event listeners /// Internally this method calls ClosePart after it removed the listeners registered /// by QmitkFunctionality. By having this proxy method the user does not have to /// call QmitkFunctionality::ClosePart() when overwriting ClosePart() /// void ClosePartProxy(); //# other protected methods which should not be overwritten (or which are deprecated) protected: /// /// Called immediately after CreateQtPartControl(). /// Here standard event listeners for a QmitkFunctionality are registered /// void AfterCreateQtPartControl(); /// /// code to activate the last visible functionality /// void ActivateLastVisibleFunctionality(); /// /// reactions to selection events from data manager (and potential other senders) /// void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection); /// /// Converts a mitk::DataNodeSelection to a std::vector (possibly empty /// std::vector DataNodeSelectionToVector(mitk::DataNodeSelection::ConstPointer currentSelection) const; //# protected fields protected: /// /// helper stuff to observe BlueBerry selections /// friend struct berry::SelectionChangedAdapter; /// - /// Saves the parent of this view (this is the scrollarea created in CreatePartControl(void*) - /// \see CreatePartControl(void*) + /// Saves the parent of this view (this is the scrollarea created in CreatePartControl(QWidget*) + /// \see CreatePartControl(QWidget*) /// QWidget* m_Parent; /// /// Saves if this view is the currently active one. /// bool m_Active; /// /// Saves if this view is visible /// bool m_Visible; //# private fields: private: /// /// Holds the current selection (selection made by this Functionality !!!) /// QmitkFunctionalitySelectionProvider* m_SelectionProvider; /// /// object to observe BlueBerry selections /// QScopedPointer m_BlueBerrySelectionListener; ctkServiceTracker m_DataStorageServiceTracker; /// /// Saves if this view handles multiple datastorages /// bool m_HandlesMultipleDataStorages; /// /// Saves if this class is currently working on DataStorage changes. /// This is a protector variable to avoid recursive calls on event listener functions. bool m_InDataStorageChanged; /// /// saves all visible functionalities /// std::set m_VisibleFunctionalities; }; #endif /*QMITKFUNCTIONALITY_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp index 0f1f25cc11..a1e84cb37b 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp @@ -1,602 +1,602 @@ /*=================================================================== 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 "QmitkAbstractView.h" #include "QmitkDataNodeSelectionProvider.h" #include "internal/QmitkCommonActivator.h" #include "internal/QmitkDataNodeItemModel.h" // mitk Includes #include #include #include #include #include #include // berry Includes #include #include #include #include #include // CTK Includes #include // Qt Includes #include #include #include #include #include class QmitkAbstractViewPrivate { public: QmitkAbstractViewPrivate(QmitkAbstractView* qq) : q(qq) , m_PrefServiceTracker(QmitkCommonActivator::GetContext()) , m_DataStorageServiceTracker(QmitkCommonActivator::GetContext()) , m_Parent(0) , m_DataNodeItemModel(new QmitkDataNodeItemModel) , m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel)) , m_InDataStorageChanged(false) { m_PrefServiceTracker.open(); m_DataStorageServiceTracker.open(); } ~QmitkAbstractViewPrivate() { delete m_DataNodeSelectionModel; delete m_DataNodeItemModel; m_PrefServiceTracker.close(); m_DataStorageServiceTracker.close(); } /** * Called when a DataStorage Add Event was thrown. Sets * m_InDataStorageChanged to true and calls NodeAdded afterwards. * \see m_InDataStorageChanged */ void NodeAddedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeAdded(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage remove event was thrown. Sets * m_InDataStorageChanged to true and calls NodeRemoved afterwards. * \see m_InDataStorageChanged */ void NodeRemovedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeRemoved(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * Called when a DataStorage changed event was thrown. Sets * m_InDataStorageChanged to true and calls NodeChanged afterwards. * \see m_InDataStorageChanged */ void NodeChangedProxy(const mitk::DataNode* node) { // garantuee no recursions when a new node event is thrown in NodeAdded() if(!m_InDataStorageChanged) { m_InDataStorageChanged = true; q->NodeChanged(node); q->DataStorageModified(); m_InDataStorageChanged = false; } } /** * reactions to selection events from views */ void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast(q)) return; if(selection.IsNull()) { q->OnNullSelection(sourcepart); return; } mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection)); } /** * Converts a mitk::DataNodeSelection to a QList (possibly empty) */ QList DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const; QmitkAbstractView* const q; ctkServiceTracker m_PrefServiceTracker; ctkServiceTracker m_DataStorageServiceTracker; /** - * Saves the parent of this view (this is the scrollarea created in CreatePartControl(void*) - * \see CreatePartControl(void*) + * Saves the parent of this view (this is the scrollarea created in CreatePartControl(QWidget*) + * \see CreatePartControl(QWidget*) */ QWidget* m_Parent; /** * Holds the current selection (selection made by this View !!!) */ QmitkDataNodeSelectionProvider::Pointer m_SelectionProvider; /** * Holds a helper model for firing selection events. */ QmitkDataNodeItemModel* m_DataNodeItemModel; /** * The selection model for the QmitkDataNodeItemModel; */ QItemSelectionModel* m_DataNodeSelectionModel; /** * object to observe BlueBerry selections */ QScopedPointer m_BlueBerrySelectionListener; /** * Saves if this class is currently working on DataStorage changes. * This is a protector variable to avoid recursive calls on event listener functions. */ bool m_InDataStorageChanged; }; QmitkAbstractView::QmitkAbstractView() : d(new QmitkAbstractViewPrivate(this)) { } -void QmitkAbstractView::CreatePartControl(void* parent) +void QmitkAbstractView::CreatePartControl(QWidget* parent) { // scrollArea QScrollArea* scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent d->m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(d->m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(d->m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); QVBoxLayout* parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkAbstractView::AfterCreateQtPartControl() { this->SetSelectionProvider(); // REGISTER DATASTORAGE LISTENER this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS d->m_BlueBerrySelectionListener.reset(new berry::NullSelectionChangedAdapter( d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener.data()); // EMULATE INITIAL SELECTION EVENTS // send the current selection berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart(); if (activePart.IsNotNull()) { this->OnSelectionChanged(activePart, this->GetCurrentSelection()); } // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } QmitkAbstractView::~QmitkAbstractView() { this->Register(); this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) ); this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) ); this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener( berry::MessageDelegate1(this, &QmitkAbstractView::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(NULL)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { s->RemovePostSelectionListener(d->m_BlueBerrySelectionListener.data()); } this->UnRegister(false); } void QmitkAbstractView::SetSelectionProvider() { // REGISTER A SELECTION PROVIDER d->m_SelectionProvider = QmitkDataNodeSelectionProvider::Pointer(new QmitkDataNodeSelectionProvider); d->m_SelectionProvider->SetItemSelectionModel(GetDataNodeSelectionModel()); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(d->m_SelectionProvider)); } QItemSelectionModel *QmitkAbstractView::GetDataNodeSelectionModel() const { return 0; } void QmitkAbstractView::OnPreferencesChanged( const berry::IBerryPreferences* ) { } void QmitkAbstractView::DataStorageModified() { } void QmitkAbstractView::DataStorageChanged(mitk::IDataStorageReference::Pointer /*dsRef*/) { } mitk::IRenderWindowPart* QmitkAbstractView::GetRenderWindowPart( IRenderWindowPartStrategies strategies ) const { berry::IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); // Return the active editor if it implements mitk::IRenderWindowPart mitk::IRenderWindowPart* renderPart = dynamic_cast(page->GetActiveEditor().GetPointer()); if (renderPart) return renderPart; // No suitable active editor found, check visible editors QList editors = page->GetEditorReferences(); for (QList::iterator i = editors.begin(); i != editors.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderPart = dynamic_cast(part.GetPointer()); if (renderPart) return renderPart; } } // No suitable visible editor found, check visible views QList views = page->GetViewReferences(); for(QList::iterator i = views.begin(); i != views.end(); ++i) { berry::IWorkbenchPart::Pointer part = (*i)->GetPart(false); if (page->IsPartVisible(part)) { renderPart = dynamic_cast(part.GetPointer()); if (renderPart) return renderPart; } } // No strategies given if (strategies == NONE) return 0; mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(GetDataStorageReference())); bool activate = false; if(strategies & ACTIVATE) { activate = true; } berry::IEditorPart::Pointer editorPart; if(strategies & OPEN) { // This will create a default editor for the given input. If an editor // with that input is already open, the editor is brought to the front. try { editorPart = mitk::WorkbenchUtil::OpenEditor(page, input, activate); } catch (const berry::PartInitException&) { // There is no editor registered which can handle the given input. } } else if (activate || (strategies & BRING_TO_FRONT)) { // check if a suitable editor is already opened editorPart = page->FindEditor(input); if (editorPart) { if (activate) { page->Activate(editorPart); } else { page->BringToTop(editorPart); } } } return dynamic_cast(editorPart.GetPointer()); } void QmitkAbstractView::RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType) { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart == 0) return; if (mitk::IRenderingManager* renderingManager = renderPart->GetRenderingManager()) { renderingManager->RequestUpdateAll(requestType); } else { renderPart->RequestUpdate(requestType); } } void QmitkAbstractView::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkAbstractView::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkAbstractView::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkAbstractView::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkAbstractView::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkAbstractView::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkAbstractView::GetPreferences() const { berry::IPreferencesService* prefService = d->m_PrefServiceTracker.getService(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const QString id = "/" + (const_cast(this))->GetViewSite()->GetId(); return prefService ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); } mitk::DataStorage::Pointer QmitkAbstractView::GetDataStorage() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != 0) { return dsService->GetDataStorage()->GetDataStorage(); } return 0; } mitk::IDataStorageReference::Pointer QmitkAbstractView::GetDataStorageReference() const { mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService(); if (dsService != 0) { return dsService->GetDataStorage(); } return mitk::IDataStorageReference::Pointer(0); } QList QmitkAbstractView::GetCurrentSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection()); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsCurrentSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); } QList QmitkAbstractView::GetDataManagerSelection() const { berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast(); return d->DataNodeSelectionToQList(currentSelection); } bool QmitkAbstractView::IsDataManagerSelectionValid() const { return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager"); } void QmitkAbstractView::SetDataManagerSelection(const berry::ISelection::ConstPointer &selection, QItemSelectionModel::SelectionFlags flags) const { berry::IViewPart::Pointer datamanagerView = this->GetSite()->GetWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.datamanager"); if (datamanagerView.IsNull()) return; datamanagerView->GetSite()->GetSelectionProvider().Cast()->SetSelection(selection, flags); } void QmitkAbstractView::SynchronizeDataManagerSelection() const { berry::ISelection::ConstPointer currentSelection = this->GetSite()->GetSelectionProvider()->GetSelection(); if (currentSelection.IsNull()) return; SetDataManagerSelection(currentSelection); } void QmitkAbstractView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& /*nodes*/) { } void QmitkAbstractView::OnNullSelection(berry::IWorkbenchPart::Pointer /*part*/) { } QList QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const { if (currentSelection.IsNull()) return QList(); return QList::fromStdList(currentSelection->GetSelectedDataNodes()); } void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ ) { } void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node ) { QList nodes; nodes << node; this->FireNodesSelected(nodes); } void QmitkAbstractView::FireNodesSelected( const QList& nodes ) { // if this is the first call to FireNodesSelected and the selection provider has no QItemSelectiomMode // yet, set our helper model if (d->m_SelectionProvider->GetItemSelectionModel() == 0) { d->m_SelectionProvider->SetItemSelectionModel(d->m_DataNodeSelectionModel); } else if (d->m_SelectionProvider->GetItemSelectionModel() != d->m_DataNodeSelectionModel) { MITK_WARN << "A custom data node selection model has been set. Ignoring call to FireNodesSelected()."; return; } if (nodes.empty()) { d->m_DataNodeSelectionModel->clearSelection(); d->m_DataNodeItemModel->clear(); } else { // The helper data node model is just used for sending selection events. // We add the to be selected nodes and set the selection range to everything. d->m_DataNodeItemModel->clear(); foreach(mitk::DataNode::Pointer node, nodes) { d->m_DataNodeItemModel->AddDataNode(node); } d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size()-1, 0)), QItemSelectionModel::ClearAndSelect); } } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h index 6a95eea73f..a4f7b3fde3 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.h @@ -1,391 +1,391 @@ /*=================================================================== 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. ===================================================================*/ #ifndef QMITKABSTRACTVIEW_H_ #define QMITKABSTRACTVIEW_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include "mitkIRenderWindowPart.h" #include #include #include #include namespace mitk { class DataNode; } namespace berry { struct IBerryPreferences; } class QmitkAbstractViewPrivate; class QmitkAbstractViewSelectionProvider; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK related BlueBerry Views. * * QmitkAbstractView provides several convenience methods that ease the introduction of a new view: * *
      *
    1. Access to the DataStorage (~ the shared data repository) *
    2. Access to the active IRenderWindowPart *
    3. Access to and update notification for the view's preferences *
    4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService *
    5. Access to and update notification for DataNode events (added/removed/modified) *
    6. Methods to send DataNode selections through the SelectionService *
    7. Some minor important convenience methods (like changing the mouse cursor/exception handling) *
    * * Usually all MITK Views inherit from QmitkAbstractView to achieve a consistent Workbench behavior. * * When inheriting from QmitkAbstractView, you must implement the following methods: *
      *
    • void CreateQtPartControl(QWidget* parent) *
    • void SetFocus() *
    * * You may reimplement the following private virtual methods to customize your View's behavior: *
      *
    • void SetSelectionProvider() *
    • QItemSelectionModel* GetDataNodeSelectionModel() const *
    * * You may reimplement the following private virtual methods to be notified about certain changes: *
      *
    • void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) *
    • void OnNullSelection(berry::IWorkbenchPart::Pointer part) *
    • void OnPreferencesChanged(const berry::IBerryPreferences*) *
    • void NodeAdded(const mitk::DataNode* node) *
    • void NodeChanged(const mitk::DataNode* node) *
    • void NodeRemoved(const mitk::DataNode* node) *
    • void DataStorageModified() *
    • void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef) *
    * * \see mitk::ILifecycleAwarePart * \see mitk::IZombieViewPart * \see mitk::IRenderWindowPartListener */ class MITK_QT_COMMON QmitkAbstractView : public berry::QtViewPart { public: /** * Describes the strategies to be used for getting a mitk::IRenderWindowPart * instance. */ enum IRenderWindowPartStrategy { /** Do nothing. */ NONE = 0x00000000, /** Bring the most recently activated mitk::IRenderWindowPart instance to the front. */ BRING_TO_FRONT = 0x00000001, /** Activate a mitk::IRenderWindowPart part (implies bringing it to the front). */ ACTIVATE = 0x00000002, /** Create a mitk::IRenderWindowPart if none is alredy opened. */ OPEN = 0x00000004 }; Q_DECLARE_FLAGS(IRenderWindowPartStrategies, IRenderWindowPartStrategy) /** * Creates smartpointer typedefs */ berryObjectMacro(QmitkAbstractView); /** * Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) * \see berry::QtViewPart::CreateQtPartControl(QWidget*) */ QmitkAbstractView(); /** * Disconnects all standard event listeners */ virtual ~QmitkAbstractView(); protected: /** * Informs other parts of the workbench that node is selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ void FireNodeSelected(mitk::DataNode::Pointer node); /** * Informs other parts of the workbench that the nodes are selected via the blueberry selection service. * * \note This method should not be used if you have set your own selection provider via * SetSelectionProvider() or your own QItemSelectionModel via GetDataNodeSelectionModel(). */ virtual void FireNodesSelected(const QList& nodes); /** * \return The selection of the currently active part of the workbench or an empty list * if there is no selection or if it is empty. * * \see IsCurrentSelectionValid */ QList GetCurrentSelection() const; /** * Queries the state of the current selection. * * \return If the current selection is NULL, this method returns * false and true otherwise. */ bool IsCurrentSelectionValid() const; /** * Returns the current selection made in the datamanager bundle or an empty list * if there is no selection or if it is empty. * * \see IsDataManagerSelectionValid */ QList GetDataManagerSelection() const; /** * Queries the state of the current selection of the data manager view. * * \return If the current data manager selection is NULL, this method returns * false and true otherwise. */ bool IsDataManagerSelectionValid() const; /** * Sets the selection of the data manager view if available. * * \param selection The new selection for the data manager. * \param flags The Qt selection flags for controlling the way how the selection is updated. */ void SetDataManagerSelection(const berry::ISelection::ConstPointer& selection, QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect) const; /** * Takes the current selection and sets it on the data manager. Only matching nodes in the * data manager view will be selected. */ void SynchronizeDataManagerSelection() const; /** * Returns the Preferences object for this View. * Important: When refering to this preferences, e.g. in a PreferencePage: The ID * for this preferences object is "/", e.g. "/org.mitk.views.datamanager" */ berry::IPreferences::Pointer GetPreferences() const; /** * Returns a reference to the currently active DataStorage. */ mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Returns the currently active DataStorage. */ mitk::DataStorage::Pointer GetDataStorage() const; /** * Returns the currently active mitk::IRenderWindowPart. * * \param strategies Strategies for returning a mitk::IRenderWindowPart instance if there * is currently no active one. * \return The active mitk::IRenderWindowPart. */ mitk::IRenderWindowPart* GetRenderWindowPart(IRenderWindowPartStrategies strategies = NONE) const; /** * Request an update of all render windows of the currently active IRenderWindowPart. * * \param requestType Specifies the type of render windows for which an update * will be requested. */ void RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Outputs an error message to the console and displays a message box containing * the exception description. * \param e the exception which should be handled * \param showDialog controls, whether additionally a message box should be * displayed to inform the user that something went wrong */ void HandleException( std::exception& e, QWidget* parent = NULL, bool showDialog = true ) const; /** * Calls HandleException ( std::exception&, QWidget*, bool ) internally * \see HandleException ( std::exception&, QWidget*, bool ) */ void HandleException( const char* str, QWidget* parent = NULL, bool showDialog = true ) const; /** * Convenient method to set and reset a wait cursor ("hourglass") */ void WaitCursorOn(); /** * Convenient method to restore the standard cursor */ void WaitCursorOff(); /** * Convenient method to set and reset a busy cursor */ void BusyCursorOn(); /** * Convenient method to restore the standard cursor */ void BusyCursorOff(); /** * Convenient method to restore the standard cursor */ void RestoreOverrideCursor(); private: /** * Reimplement this method to set a custom selection provider. This method is * called once after CreateQtPartControl(). * * The default implementation registers a QmitkDataNodeSelectionProvider with * a QItemSelectionModel returned by GetDataNodeSelectionModel(). */ virtual void SetSelectionProvider(); /** * Reimplement this method to supply a custom Qt selection model. The custom * model will be used with the default selection provider QmitkDataNodeSelectionProvider * to inform the MITK Workbench about selection changes. * * If you reimplement this method, the methods FireNodeSelected() and FireNodesSelected() * will have no effect. Use your custom selection model to notify the MITK Workbench * about selection changes. * * The Qt item model used with the custom selection model must return mitk::DataNode::Pointer * objects for model indexes when the role is QmitkDataNodeRole. */ virtual QItemSelectionModel* GetDataNodeSelectionModel() const; /** * Called when the selection in the workbench changed. * May be reimplemented by deriving classes. * * \param part The source part responsible for the selection change. * \param nodes A list of selected nodes. * * \see OnNullSelection */ virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes); /** * Called when a NULL selection occurs. * * \param part The source part responsible for the selection change. */ virtual void OnNullSelection(berry::IWorkbenchPart::Pointer part); /** * Called when the preferences object of this view changed. * May be reimplemented by deriving classes. * * \see GetPreferences() */ virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /** * Called when a DataStorage Add event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeAdded(const mitk::DataNode* node); /** * Called when a DataStorage Changed event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeChanged(const mitk::DataNode* node); /** * Called when a DataStorage Remove event was thrown. May be reimplemented * by deriving classes. */ virtual void NodeRemoved(const mitk::DataNode* node); /** * Called when a DataStorage add *or* remove *or* change event from the currently active * data storage is thrown. * * May be reimplemented by deriving classes. */ virtual void DataStorageModified(); /** * Called when the currently active DataStorage changed. * May be reimplemented by deriving classes. * * \param dsRef A reference to the new active DataStorage. */ virtual void DataStorageChanged(mitk::IDataStorageReference::Pointer dsRef); /** * Creates a scroll area for this view and calls CreateQtPartControl then */ - void CreatePartControl(void* parent); + void CreatePartControl(QWidget* parent); /** * Called immediately after CreateQtPartControl(). * Here standard event listeners for a QmitkAbstractView are registered */ void AfterCreateQtPartControl(); private: friend class QmitkAbstractViewPrivate; friend class QmitkViewCoordinator; Q_DISABLE_COPY(QmitkAbstractView) const QScopedPointer d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QmitkAbstractView::IRenderWindowPartStrategies) #endif /*QMITKABSTRACTVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp index 418b1b9683..74926c226f 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp @@ -1,84 +1,85 @@ /*=================================================================== 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 "QmitkDiffusionImagingAppWorkbenchAdvisor.h" #include "internal/QmitkDiffusionApplicationPlugin.h" #include #include #include #include #include +#include const QString QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; void QmitkDiffusionImagingAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkDiffusionImagingAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QList perspExcludeList; perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective" ); perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective2" ); // perspExcludeList.push_back( std::string("org.mitk.coreapp.defaultperspective") ); //perspExcludeList.push_back( std::string("org.mitk.extapp.defaultperspective") ); perspExcludeList.push_back( "org.mitk.perspectives.publicdiffusionimaging" ); perspExcludeList.push_back("org.mitk.perspectives.diffusionimaginginternal" ); // Exclude the help perspective from org.blueberry.ui.qt.help from // the normal perspective list. // The perspective gets a dedicated menu entry in the help menu perspExcludeList.push_back("org.blueberry.perspectives.help"); QList viewExcludeList; viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview" ); viewExcludeList.push_back( "org.mitk.views.imagenavigator" ); // viewExcludeList.push_back( std::string("org.mitk.views.datamanager") ); viewExcludeList.push_back( "org.mitk.views.modules" ); viewExcludeList.push_back( "org.blueberry.ui.internal.introview" ); - configurer->SetInitialSize(berry::Point(1000,770)); + configurer->SetInitialSize(QPoint(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->ShowViewMenuItem(true); advisor->ShowNewWindowMenuItem(true); advisor->ShowClosePerspectiveMenuItem(true); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowPerspectiveToolbar(false); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->ShowMemoryIndicator(false); advisor->SetProductName("MITK Diffusion"); advisor->SetWindowIcon(":/org.mitk.gui.qt.diffusionimagingapp/app-icon.png"); return advisor; } QString QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index 0d1fbed4ed..febbe0277b 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1356 +1,1356 @@ /*=================================================================== 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 "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack * QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForViewNavigator: public berry::IPartListener { public: PartListenerForViewNavigator(QAction* act) : viewNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } private: QAction* viewNavigatorAction; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa), perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } //GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->viewNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { QList perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->viewNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer), lastInput(0), wbAdvisor(wbAdvisor), showViewToolbar(true), showPerspectiveToolbar(false), showVersionInfo(true), showMitkVersionInfo(true), showViewMenuItem(true), showNewWindowMenuItem(false), showClosePerspectiveMenuItem(true), viewNavigatorFound(false), showMemoryIndicator(true), dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName(); viewExcludeList.push_back("org.mitk.views.viewnavigatorview"); } QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor() { } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { //berry::ActionBarAdvisor::Pointer actionBarAdvisor( // new QmitkExtActionBarAdvisor(configurer)); //return actionBarAdvisor; return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer); } -void* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(void* parent) +QWidget* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent) { QWidget* parentWidget = static_cast(parent); QLabel* label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show) { showMemoryIndicator = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowMemoryIndicator() { return showMemoryIndicator; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const QString& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = qobject_cast (window->GetShell()->GetControl()); window->SetPerspectiveExcludeList(perspectiveExcludeList); window->SetViewExcludeList(viewExcludeList); if (!windowIcon.isEmpty()) { mainWindow->setWindowIcon(QIcon(windowIcon)); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); /*mainWindow->setStyleSheet("color: white;" "background-color: #808080;" "selection-color: #659EC7;" "selection-background-color: #808080;" " QMenuBar {" "background-color: #808080; }");*/ // Load selected icon theme QStringList searchPaths = QIcon::themeSearchPaths(); searchPaths.push_front( QString(":/org_mitk_icons/icons/") ); QIcon::setThemeSearchPaths( searchPaths ); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); QString iconTheme = stylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>"); if( iconTheme == QString( "<>" ) ) { iconTheme = QString( "tango" ); } QIcon::setThemeName( iconTheme ); // ==== Application menu ============================ QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); QAction* fileOpenAction = new QmitkFileOpenAction(QIcon::fromTheme("document-open",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-open.svg")), window); fileOpenAction->setShortcut(QKeySequence::Open); fileMenu->addAction(fileOpenAction); QAction* fileSaveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.ext/Save_48.png"), window); fileSaveAction->setShortcut(QKeySequence::Save); fileMenu->addAction(fileSaveAction); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(QIcon::fromTheme("document-save",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-save.svg"))); fileMenu->addAction(fileSaveProjectAction); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(QIcon::fromTheme("edit-delete",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-delete.svg"))); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(QIcon::fromTheme("system-log-out",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/system-log-out.svg"))); fileExitAction->setShortcut(QKeySequence::Quit); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { openDicomEditorAction = new QmitkOpenDicomEditorAction(QIcon(":/org.mitk.gui.qt.ext/dcm-icon.png"),window); } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { openXnatEditorAction = new QmitkOpenXnatEditorAction(QIcon(":/org.mitk.gui.qt.ext/xnat-icon.png"),window); } berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const QList viewDescriptors = viewRegistry->GetViews(); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(QIcon::fromTheme("edit-undo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-undo.svg")), "&Undo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(QIcon::fromTheme("edit-redo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-redo.svg")) , "&Redo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); } viewNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/view-manager_48.png"),"&View Navigator", NULL); viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigatorview"); if (viewNavigatorFound) { QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator())); viewNavigatorAction->setCheckable(true); // add part listener for view navigator viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction)); window->GetPartService()->AddPartListener(viewNavigatorPartListener.data()); berry::IViewPart::Pointer viewnavigatorview = window->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); viewNavigatorAction->setChecked(false); if (viewnavigatorview) { bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); if (isViewNavigatorVisible) viewNavigatorAction->setChecked(true); } viewNavigatorAction->setToolTip("Toggle View Navigator"); } // toolbar for showing file open, undo, redo and other main actions QToolBar* mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif mainActionsToolBar->addAction(fileOpenAction); mainActionsToolBar->addAction(fileSaveProjectAction); mainActionsToolBar->addAction(closeProjectAction); mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { mainActionsToolBar->addAction(openDicomEditorAction); } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { mainActionsToolBar->addAction(openXnatEditorAction); } if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } if (viewNavigatorFound) mainActionsToolBar->addAction(viewNavigatorAction); mainWindow->addToolBar(mainActionsToolBar); #ifdef __APPLE__ #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) mainWindow->setUnifiedTitleAndToolBarOnMac(true); // default is false #endif #endif // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); if (showNewWindowMenuItem) { windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); windowMenu->addSeparator(); } QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); QMenu* viewMenu; if (showViewMenuItem) { viewMenu = windowMenu->addMenu("Show &View"); viewMenu->setObjectName("Show View"); } windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); if(showClosePerspectiveMenuItem) closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QActionGroup* perspGroup = new QActionGroup(menuBar); QList perspectives( perspRegistry->GetPerspectives()); bool skip = false; for (QList::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction); } perspMenu->addActions(perspGroup->actions()); // sort elements (converting vector to map...) QList::const_iterator iter; std::map VDMap; skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; if ((*iter)->GetId() == "org.mitk.views.viewnavigatorview") continue; std::pair p( (*iter)->GetLabel(), (*iter)); VDMap.insert(p); } // ==== Perspective Toolbar ================================== QToolBar* qPerspectiveToolbar = new QToolBar; qPerspectiveToolbar->setObjectName("perspectiveToolBar"); if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; // ==== View Toolbar ================================== QToolBar* qToolbar = new QToolBar; qToolbar->setObjectName("viewToolBar"); std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); if(showViewMenuItem) viewMenu->addAction(viewAction); if (showViewToolbar) { qToolbar->addAction(viewAction); } } if (showViewToolbar) { mainWindow->addToolBar(qToolbar); } else delete qToolbar; QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("&Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this)); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data()); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener.data()); } void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen() { berry::WorkbenchWindowAdvisor::PostWindowOpen(); // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // get ImageNavigatorView berry::IViewPart::Pointer imageNavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); if (imageNavigatorView) { bool isImageNavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(imageNavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagenavigator"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator() { // get viewnavigatorView berry::IViewPart::Pointer viewnavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); if (viewnavigatorView) { bool isviewnavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(viewnavigatorView); if (isviewnavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(viewnavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.viewnavigatorview"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(0); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(NULL, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == 0) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),NULL); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); //titlePerspectiveListener = new PerspectiveListenerForTitle(this); editorPropertyListener.reset(new berry::PropertyChangeIntAdapter< QmitkExtWorkbenchWindowAdvisor>(this, &QmitkExtWorkbenchWindowAdvisor::PropertyChange)); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); //configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data()); } QString QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } QString title; //TODO Product // IProduct product = Platform.getProduct(); // if (product != null) { // title = product.getName(); // } // instead of the product name, we use a custom variable for now title = productName; if(showMitkVersionInfo) { title += QString(" ") + MITK_VERSION_STRING; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 VTK %4.%5.%6 Qt %7 MITK %8)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR) .arg(MITK_VERSION_STRING); title += versions; } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.isEmpty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); QString label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.isEmpty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); QString oldTitle = configurer->GetTitle(); QString newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = 0; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = 0; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } if (!lastActiveEditor.Expired()) { lastActiveEditor.Lock()->RemovePropertyListener(editorPropertyListener.data()); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener.data()); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { if (!lastActiveEditor.Expired()) { QString newTitle = lastActiveEditor.Lock()->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList& v) { this->perspectiveExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(const QList& v) { this->viewExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h index 061c651798..eabd97bf09 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.h @@ -1,180 +1,180 @@ /*=================================================================== 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. ===================================================================*/ #ifndef QMITKEXTWORKBENCHWINDOWADVISOR_H_ #define QMITKEXTWORKBENCHWINDOWADVISOR_H_ #include #include #include #include #include #include #include #include class QAction; class QMenu; class MITK_QT_COMMON_EXT_EXPORT QmitkExtWorkbenchWindowAdvisor : public QObject, public berry::WorkbenchWindowAdvisor { Q_OBJECT public: QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer); ~QmitkExtWorkbenchWindowAdvisor(); berry::SmartPointer CreateActionBarAdvisor( berry::SmartPointer configurer); - void* CreateEmptyWindowContents(void* parent); + QWidget* CreateEmptyWindowContents(QWidget* parent); void PostWindowCreate(); void PreWindowOpen(); void PostWindowOpen(); void PostWindowClose(); void ShowViewToolbar(bool show); void ShowPerspectiveToolbar(bool show); void ShowVersionInfo(bool show); void ShowMitkVersionInfo(bool show); void ShowViewMenuItem(bool show); void ShowNewWindowMenuItem(bool show); void ShowClosePerspectiveMenuItem(bool show); bool GetShowClosePerspectiveMenuItem(); void ShowMemoryIndicator(bool show); bool GetShowMemoryIndicator(); //TODO should be removed when product support is here void SetProductName(const QString& product); void SetWindowIcon(const QString& wndIcon); void SetPerspectiveExcludeList(const QList &v); QList GetPerspectiveExcludeList(); void SetViewExcludeList(const QList &v); QList GetViewExcludeList(); protected slots: virtual void onIntro(); virtual void onHelp(); virtual void onHelpOpenHelpPerspective(); virtual void onAbout(); private: /** * Hooks the listeners needed on the window * * @param configurer */ void HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer); QString ComputeTitle(); void RecomputeTitle(); QString GetQSettingsFile() const; /** * Updates the window title. Format will be: [pageInput -] * [currentPerspective -] [editorInput -] [workspaceLocation -] productName * @param editorHidden TODO */ void UpdateTitle(bool editorHidden); void PropertyChange(const berry::Object::Pointer& /*source*/, int propId); static QString QT_SETTINGS_FILENAME; QScopedPointer titlePartListener; QScopedPointer titlePerspectiveListener; QScopedPointer menuPerspectiveListener; QScopedPointer imageNavigatorPartListener; QScopedPointer viewNavigatorPartListener; QScopedPointer editorPropertyListener; friend struct berry::PropertyChangeIntAdapter; friend class PartListenerForTitle; friend class PerspectiveListenerForTitle; friend class PerspectiveListenerForMenu; friend class PartListenerForImageNavigator; friend class PartListenerForViewNavigator; berry::IEditorPart::WeakPtr lastActiveEditor; berry::IPerspectiveDescriptor::WeakPtr lastPerspective; berry::IWorkbenchPage::WeakPtr lastActivePage; QString lastEditorTitle; berry::IAdaptable* lastInput; berry::WorkbenchAdvisor* wbAdvisor; bool showViewToolbar; bool showPerspectiveToolbar; bool showVersionInfo; bool showMitkVersionInfo; bool showViewMenuItem; bool showNewWindowMenuItem; bool showClosePerspectiveMenuItem; bool viewNavigatorFound; bool showMemoryIndicator; QString productName; QString windowIcon; // enables DnD on the editor area QScopedPointer dropTargetListener; // stringlist for excluding perspectives from the perspective menu entry (e.g. Welcome Perspective) QList perspectiveExcludeList; // stringlist for excluding views from the menu entry QList viewExcludeList; // maps perspective ids to QAction objects QHash mapPerspIdToAction; // actions which will be enabled/disabled depending on the application state QList viewActions; QAction* fileSaveProjectAction; QAction* closeProjectAction; QAction* undoAction; QAction* redoAction; QAction* imageNavigatorAction; QAction* viewNavigatorAction; QAction* resetPerspAction; QAction* closePerspAction; QAction* openDicomEditorAction; QAction* openXnatEditorAction; }; #endif /*QMITKEXTWORKBENCHWINDOWADVISOR_H_*/