diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp index 8850ca72fb..bf1c153c4a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp @@ -1,531 +1,531 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWindow.h" #include "berryConstants.h" #include "berrySameShellProvider.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" namespace berry { const int Window::OK = 0; const int Window::CANCEL = 1; std::vector Window::defaultImages = std::vector(); Window::IExceptionHandler::Pointer Window::exceptionHandler(new DefaultExceptionHandler()); IShellProvider::Pointer Window::defaultModalParent(new DefaultModalParent()); Window::WindowShellListener::WindowShellListener(Window* wnd) : window(wnd) { } void Window::WindowShellListener::ShellClosed(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() { 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 std::vector& 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 std::vector 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(); } 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); // } } //voidWindow::ConstrainShellSize() //{ // // limit the shell size to the display size // Rectangle bounds = shell.getBounds(); // Rectangle constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} void* Window::CreateContents(Shell::Pointer parent) { // by default, just create a composite //return new Composite(parent, SWT.NONE); return parent->GetControl(); } Shell::Pointer Window::CreateShell() { Shell::Pointer newParent = this->GetParentShell(); // if (newParent != 0 && newParent.isDisposed()) // { // parentShell = new SameShellProvider(null); // newParent = getParentShell();//Find a better parent // } //Create the shell Shell::Pointer newShell = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(newParent, this->GetShellStyle()); // resizeListener = new Listener() { // public void handleEvent(Event e) { // resizeHasOccurred = true; // } // }; //newShell.addListener(SWT.Resize, resizeListener); newShell->SetData(Object::Pointer(this)); //Add a listener newShell->AddShellListener(this->GetShellListener()); //Set the layout this->ConfigureShell(newShell); // //Register for font changes // if (fontChangeListener == null) // { // fontChangeListener = new FontChangeListener(); // } // JFaceResources.getFontRegistry().addListener(fontChangeListener); return newShell; } void* Window::GetContents() { return contents; } Point Window::GetInitialLocation(const Point& initialSize) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); Point centerPoint(0,0); Rectangle parentBounds(0,0,0,0); if (parent != 0) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); centerPoint.x = parentBounds.x + parentBounds.width/2; centerPoint.y = parentBounds.y - parentBounds.height/2; } else { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY) ->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber()); centerPoint.x = parentBounds.width/2; centerPoint.y = parentBounds.height/2; } return Point(centerPoint.x - (initialSize.x / 2), std::max(parentBounds.y, std::min(centerPoint.y - (initialSize.y * 2 / 3), parentBounds.y + parentBounds.height - initialSize.y))); } Point 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::Pointer Window::GetShellListener() { if (windowShellListener == 0) windowShellListener = new WindowShellListener(this); return windowShellListener; } int Window::GetShellStyle() { return shellStyle; } void Window::HandleShellCloseEvent() { this->SetReturnCode(CANCEL); this->Close(); } void Window::InitializeBounds() { // if (resizeListener != null) // { // shell.removeListener(SWT.Resize, resizeListener); // } // if (resizeHasOccurred) // { // Check if shell size has been set already. // return; // } Point size = this->GetInitialSize(); Point location = this->GetInitialLocation(size); shell->SetBounds(this->GetConstrainedShellBounds(Rectangle(location.x, location.y, size.x, size.y))); } Rectangle Window::GetConstrainedShellBounds(const Rectangle& preferredSize) { Rectangle result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); Rectangle bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); if (result.height > bounds.height) { result.height = bounds.height; } if (result.width > bounds.width) { result.width = bounds.width; } result.x = std::max(bounds.x, std::min(result.x, bounds.x + bounds.width - result.width)); result.y = std::max(bounds.y, std::min(result.y, bounds.y + bounds.height - result.height)); 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; } bool Window::Close() { - BERRY_INFO << "Window::Close()"; +// BERRY_INFO << "Window::Close()"; // // stop listening for font changes // if (fontChangeListener != null) // { // JFaceResources.getFontRegistry().removeListener(fontChangeListener); // fontChangeListener = null; // } // remove this window from a window manager if it has one if (windowManager != 0) { windowManager->Remove(Window::Pointer(this)); windowManager = 0; } if (shell == 0) { return true; } shell->RemoveShellListener(this->GetShellListener()); shell->SetData(Object::Pointer(0)); // If we "close" the shell recursion will occur. // Instead, we need to "dispose" the shell to remove it from the // display. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->DisposeShell(shell); shell = 0; contents = 0; return true; } void Window::Create() { shell = this->CreateShell(); contents = this->CreateContents(shell); //initialize the bounds of the shell to that appropriate for the // contents this->InitializeBounds(); } void* Window::GetDefaultImage() { return (defaultImages.size() < 1) ? 0 : defaultImages[0]; } std::vector Window::GetDefaultImages() { return defaultImages; } int Window::GetReturnCode() { return returnCode; } Shell::Pointer Window::GetShell() { return shell; } WindowManager* Window::GetWindowManager() { return windowManager; } int Window::Open() { if (shell == 0) { // create the window this->Create(); } // limit the shell size to the display size //constrainShellSize(); // open the window shell->Open(block); // // run the event loop if specified // if (block) // { // this->RunEventLoop(); // } return returnCode; } void Window::SetBlockOnOpen(bool shouldBlock) { block = shouldBlock; } void Window::SetDefaultImage(void* image) { if (image != 0) defaultImages.push_back(image); } void Window::SetDefaultImages(const std::vector& images) { defaultImages = images; } void Window::SetWindowManager(WindowManager* manager) { windowManager = manager; // Code to detect invalid usage if (manager != 0) { std::vector windows = manager->GetWindows(); for (unsigned 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/src/internal/berryTweaklets.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp index 8cdd2bc95e..fc1e1dc82d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp @@ -1,62 +1,62 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryTweaklets.h" namespace berry { QHash Tweaklets::defaults; QHash Tweaklets::tweaklets; TweakKey_base::TweakKey_base(const QString& _tweakClass) : tweakClass(_tweakClass) { } bool TweakKey_base::operator==(const TweakKey_base& obj) const { if (this == &obj) return true; return tweakClass == obj.tweakClass; } bool TweakKey_base::operator<(const TweakKey_base& obj) const { return tweakClass < obj.tweakClass; } void Tweaklets::SetDefault(const TweakKey_base& definition, QObject* implementation) { defaults.insert(definition, implementation); } void Tweaklets::Clear() { - std::cout << "Clearing tweaklets\n"; + // BERRY_DEBUG << "Clearing tweaklets"; tweaklets.clear(); defaults.clear(); } } uint qHash(const berry::TweakKey_base& key) { return qHash(key.tweakClass); } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp index c870944b5c..f4268f1606 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp @@ -1,1779 +1,1779 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "../tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" #include "../dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" #include "../berryImageDescriptor.h" #include "../berryDisplay.h" #include "../services/berryIServiceFactory.h" #include "../util/berrySafeRunnable.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include #include #include namespace berry { Workbench* Workbench::instance = 0; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const std::string Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const std::string Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const Poco::File& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile), result(result) { } void Run() { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format std::string version; memento->GetString(WorkbenchConstants::TAG_VERSION, version); bool valid = false; for (std::size_t i = 0; i < Workbench::VERSION_STRING_COUNT; i++) { if (Workbench::VERSION_STRING[i] == version) { valid = true; break; } } if (!valid) { input.close(); std::string msg = "Invalid workbench state version. workbench.xml will be deleted"; MessageDialog::OpenError(Shell::Pointer(0), "Restoring Problems", msg); stateFile.remove(); // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result = false; return; } // // Validate compatible version format // // We no longer support the release 1.0 format // if (VERSION_STRING[0].equals(version)) // { // reader.close(); // std::string msg = "The saved user interface layout is in an " // "obsolete format and cannot be preserved. Your projects and files " // "will not be affected. Press OK to convert to the new format. Press " // "Cancel to exit with no changes."; // std::vector dlgLabels; // dlgLabels.push_back("Ok"); // dlgLabels.push_back("Cancel"); // IDialog::Pointer dlg = MessageDialog::CreateDialog(Shell::Pointer(0), // "Cannot Preserve Layout", 0, msg, IDialog::WARNING, dlgLabels, 0); // IDialog::ReturnCode ignoreSavedState = dlg->Open(); // // OK is the default // if (ignoreSavedState == IDialog::OK) // { // stateFile.remove(); // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, // // null); // result = false; // } // else // { // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_EXIT, msg, // // null); // result = false; // } // return; // } // Restore the saved state //final IStatus restoreResult = restoreState(memento); /*bool restoreResult =*/ workbench->RestoreState(memento); input.close(); // if (restoreResult.getSeverity() == IStatus.ERROR) { // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // StatusManager.getManager().handle(restoreResult, StatusManager.LOG); // } // }); // // } } void HandleException(const std::exception& e) { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // std::string msg = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$ // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, e); result = false; stateFile.remove(); // }}); } private: void Handle(const std::exception& e) { SafeRunnable::HandleException(e); } }; int Workbench::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // create the workbench instance Workbench workbench(display, advisor); // run the workbench event loop int returnCode = workbench.RunUI(); return returnCode; } Display* Workbench::CreateDisplay() { // create the display Display* newDisplay = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDisplay(); // workaround for 1GEZ9UR and 1GF07HN //newDisplay.setWarnings(false); // Set the priority higher than normal so as to be higher // than the JobManager. //Poco::Thread::current()->setPriority(Poco::Thread::PRIO_HIGH); //initializeImages(); return newDisplay; } Workbench::ServiceLocatorOwner::ServiceLocatorOwner(Workbench* wb) : workbench(wb) { } void Workbench::ServiceLocatorOwner::Dispose() { MessageDialog::OpenInformation( Shell::Pointer(0), "Restart needed", "A required plug-in is no longer available and the Workbench needs to be restarted. You will be prompted to save if there is any unsaved work."); workbench->Close(PlatformUI::RETURN_RESTART, true); } Workbench::Workbench(Display* display, WorkbenchAdvisor* advisor) : progressCount(-1), serviceLocatorOwner(new ServiceLocatorOwner(this)), largeUpdates(0), introManager(0), isStarting(true), isClosing(false) { poco_check_ptr(display) ; poco_check_ptr(advisor); // the reference count to the one and only workbench instance // is increased, so that temporary smart pointer to the workbench // do not delete it this->Register(); this->display = display; this->advisor = advisor; Workbench::instance = this; IServiceLocatorCreator::Pointer slc(new ServiceLocatorCreator()); this->serviceLocator = slc->CreateServiceLocator(IServiceLocator::WeakPtr(), IServiceFactory::ConstPointer(0), IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(IServiceLocatorCreator::GetManifestName(), slc); returnCode = PlatformUI::RETURN_UNSTARTABLE; } Display* Workbench::GetDisplay() { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->UnRegister(false); } Object::Pointer Workbench::GetService(const std::string& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const std::string& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { bool bail = false; // create workbench window manager //windowManager = new WindowManager(); IIntroRegistry* introRegistry = WorkbenchPlugin::GetDefault() ->GetIntroRegistry(); if (introRegistry->GetIntroCount() > 0) { //TODO Product support //IProduct product = Platform.getProduct(); //if (product != null) { introDescriptor = introRegistry ->GetIntroForProduct("").Cast(); //product.getId()); //} } // TODO Correctly order service initialization // there needs to be some serious consideration given to // the services, and hooking them up in the correct order //final EvaluationService restrictionService = new EvaluationService(); //final EvaluationService evaluationService = new EvaluationService(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // serviceLocator.registerService(IRestrictionService.class, // restrictionService); // serviceLocator.registerService(IEvaluationService.class, // evaluationService); // } // }); // Initialize the activity support. //workbenchActivitySupport = new WorkbenchActivitySupport(); //activityHelper = ActivityPersistanceHelper.getInstance(); this->InitializeDefaultServices(); // initializeFonts(); // initializeColors(); // initializeApplicationColors(); // now that the workbench is sufficiently initialized, let the advisor // have a turn. advisor->InternalBasicInitialize(this->GetWorkbenchConfigurer()); // attempt to restore a previous workbench state advisor->PreStartup(); if (!advisor->OpenWindows()) { bail = true; } if (bail) return false; //forceOpenPerspective(); return true; } bool Workbench::RestoreState() { //return false; if (!GetWorkbenchConfigurer()->GetSaveAndRestore()) { // std::string msg = "This application does not save and restore previously saved state."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // Read the workbench state file. Poco::File stateFile; // If there is no state file cause one to open. if (!GetWorkbenchStateFile(stateFile) || !stateFile.exists()) { // std::string msg = "No previously saved state to restore."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // final IStatus result[] = { new Status(IStatus.OK, // WorkbenchPlugin.PI_WORKBENCH, IStatus.OK, "", null) }; //$NON-NLS-1$ bool result = true; ISafeRunnable::Pointer runnable(new RestoreStateRunnable(this, stateFile, result)); SafeRunner::Run(runnable); // ensure at least one window was opened //if (result[0].isOK() && windowManager.getWindows().length == 0) if (result && windowManager.GetWindowCount() == 0) { std::string msg = "No windows restored."; // result[0] = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result &= false; } return result; } bool Workbench::RestoreState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.Workbench_problemsRestoring, null); bool result = true; const bool showProgress = false; //TODO restore state progress // final boolean showProgress = PrefUtil.getAPIPreferenceStore() // .getBoolean( // IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); try { /* * Restored windows will be set in the createdWindows field to be * used by the openWindowsAfterRestore() method */ if (!showProgress) { DoRestoreState(memento, result); } else { // Retrieve how many plug-ins were loaded while restoring the // workbench int lastProgressCount = -1; memento->GetInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, lastProgressCount); // If we don't know how many plug-ins were loaded last time, // assume we are loading half of the installed plug-ins. /*const std::size_t expectedProgressCount =*/ std::max(1, lastProgressCount == -1 ? WorkbenchPlugin::GetDefault()->GetBundleCount() / 2 : lastProgressCount); //TODO restore state progress // RunStartupWithProgress(expectedProgressCount, new Runnable() { // public void Run() { // DoRestoreState(memento, result); // } // }); } } catch (...) { OpenWindowsAfterRestore(); throw; } OpenWindowsAfterRestore(); return result; } void Workbench::DoRestoreState(IMemento::Pointer memento, bool& status) // final MultiStatus status) { IMemento::Pointer childMem; try { // UIStats.start(UIStats.RESTORE_WORKBENCH, "MRUList"); //$NON-NLS-1$ IMemento::Pointer mruMemento = memento ->GetChild(WorkbenchConstants::TAG_MRU_LIST); if (mruMemento) { // TODO restore editor history //status.add(getEditorHistory().restoreState(mruMemento)); } //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ } catch (...) { //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ throw; } // Restore advisor state. IMemento::Pointer advisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); if (advisorState) { //status.add(getAdvisor().restoreState(advisorState)); status &= GetAdvisor()->RestoreState(advisorState); } // Get the child windows. std::vector children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (std::size_t i = 0; i < children.size(); i++) { childMem = children[i]; WorkbenchWindow::Pointer newWindow; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow = NewWorkbenchWindow(); newWindow->Create(); // }}); createdWindows.push_back(newWindow); // allow the application to specify an initial perspective to open // @issue temporary workaround for ignoring initial perspective // String initialPerspectiveId = // getAdvisor().getInitialWindowPerspectiveId(); // if (initialPerspectiveId != null) { // IPerspectiveDescriptor desc = // getPerspectiveRegistry().findPerspectiveWithId(initialPerspectiveId); // result.merge(newWindow.restoreState(childMem, desc)); // } // add the window so that any work done in newWindow.restoreState // that relies on Workbench methods has windows to work with windowManager.Add(newWindow); // now that we've added it to the window manager we need to listen // for any exception that might hose us before we get a chance to // open it. If one occurs, remove the new window from the manager. // Assume that the new window is a phantom for now try { //status.merge(newWindow[0].restoreState(childMem, null)); status &= newWindow->RestoreState(childMem, IPerspectiveDescriptor::Pointer(0)); try { newWindow->FireWindowRestored(); } catch (const WorkbenchException& /*e*/) { //status.add(e.getStatus()); status &= false; } // everything worked so far, don't close now } catch (...) { // null the window in newWindowHolder so that it won't be // opened later on createdWindows[i] = 0; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newWindow->Close(); // }}); } } } void Workbench::OpenWindowsAfterRestore() { if (createdWindows.empty()) { return; } // now open the windows (except the ones that were nulled because we // closed them above) for (std::size_t i = 0; i < createdWindows.size(); i++) { if (createdWindows[i]) { WorkbenchWindow::Pointer myWindow = createdWindows[i]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { try { myWindow->Open(); } catch (...) { myWindow->Close(); throw; } // }}); } } createdWindows.clear(); } void Workbench::InitializeDefaultServices() { // final IContributionService contributionService = new ContributionService( // getAdvisor()); // serviceLocator.registerService(IContributionService.class, // contributionService); // // // TODO Correctly order service initialization // // there needs to be some serious consideration given to // // the services, and hooking them up in the correct order // final IEvaluationService evaluationService = // (IEvaluationService) serviceLocator.getService(IEvaluationService.class); // // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { Object::Pointer service(new SaveablesList()); serviceLocator->RegisterService(ISaveablesLifecycleListener::GetManifestName(), service); // }}); // // /* // * Phase 1 of the initialization of commands. When this phase completes, // * all the services and managers will exist, and be accessible via the // * getService(Object) method. // */ // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // Command.DEBUG_COMMAND_EXECUTION = Policy.DEBUG_COMMANDS; // commandManager = new CommandManager(); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // commandService[0] = new CommandService(commandManager); // commandService[0].readRegistry(); // serviceLocator.registerService(ICommandService.class, commandService[0]); // // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // ContextManager.DEBUG = Policy.DEBUG_CONTEXTS; // contextManager = new ContextManager(); // }}); // // final IContextService contextService = new ContextService( // contextManager); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // contextService.readRegistry(); // }}); // // serviceLocator.registerService(IContextService.class, contextService); // // // final IBindingService [] bindingService = new BindingService[1]; // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS; // bindingManager = new BindingManager(contextManager, commandManager); // bindingService[0] = new BindingService( // bindingManager, commandService[0], Workbench.this); // // }}); // // bindingService[0].readRegistryAndPreferences(commandService[0]); // serviceLocator.registerService(IBindingService.class, bindingService[0]); // // final CommandImageManager commandImageManager = new CommandImageManager(); // final CommandImageService commandImageService = new CommandImageService( // commandImageManager, commandService[0]); // commandImageService.readRegistry(); // serviceLocator.registerService(ICommandImageService.class, // commandImageService); // // final WorkbenchMenuService menuService = new WorkbenchMenuService(serviceLocator); // // serviceLocator.registerService(IMenuService.class, menuService); // // the service must be registered before it is initialized - its // // initialization uses the service locator to address a dependency on // // the menu service // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // menuService.readRegistry(); // }}); // // /* // * Phase 2 of the initialization of commands. The source providers that // * the workbench provides are creating and registered with the above // * services. These source providers notify the services when particular // * pieces of workbench state change. // */ // final SourceProviderService sourceProviderService = new SourceProviderService(serviceLocator); // serviceLocator.registerService(ISourceProviderService.class, // sourceProviderService); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // // this currently instantiates all players ... sigh // sourceProviderService.readRegistry(); // ISourceProvider[] sp = sourceProviderService.getSourceProviders(); // for (int i = 0; i < sp.length; i++) { // evaluationService.addSourceProvider(sp[i]); // if (!(sp[i] instanceof ActiveContextSourceProvider)) { // contextService.addSourceProvider(sp[i]); // } // } // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // // these guys are need to provide the variables they say // // they source // actionSetSourceProvider = (ActionSetSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_ACTION_SETS_NAME); // // FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME); // serviceLocator.registerService(IFocusService.class, // focusControl); // // menuSourceProvider = (MenuSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_MENU_NAME); // }}); // // /* // * Phase 3 of the initialization of commands. This handles the creation // * of wrappers for legacy APIs. By the time this phase completes, any // * code trying to access commands through legacy APIs should work. // */ // final IHandlerService[] handlerService = new IHandlerService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // handlerService[0] = (IHandlerService) serviceLocator // .getService(IHandlerService.class); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); // // addWindowListener(windowListener); // bindingManager.addBindingManagerListener(bindingManagerListener); // // serviceLocator.registerService(ISelectionConversionService.class, // new SelectionConversionService()); } int Workbench::RunUI() { // initialize workbench and restore or open one window bool initOK = this->Init(); // let the advisor run its start up code if (initOK) { advisor->PostStartup(); // may trigger a close/restart } //TODO start eager plug-ins //startPlugins(); //addStartupRegistryListener(); isStarting = false; BERRY_INFO << "BlueBerry Workbench ready"; this->GetWorkbenchTestable()->Init(Display::GetDefault(), this); // spin event loop return display->RunEventLoop(); } std::string Workbench::GetDefaultPerspectiveId() { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } IAdaptable* Workbench::GetDefaultPageInput() { return this->GetAdvisor()->GetDefaultPageInput(); } std::string Workbench::GetPresentationId() { if (factoryID != "") { return factoryID; } //factoryID = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID); // Workaround for bug 58975 - New preference mechanism does not properly // initialize defaults // Ensure that the UI plugin has started too. factoryID = WorkbenchConstants::DEFAULT_PRESENTATION_ID; return factoryID; } void Workbench::UpdateTheme() { WorkbenchPlugin::GetDefault()->GetPresentationFactory()->UpdateTheme(); } void Workbench::LargeUpdateStart() { if (largeUpdates++ == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(false); // workbenchContextSupport.setProcessing(false); std::vector windows = this->GetWorkbenchWindows(); for (unsigned int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateStart(); } } } } void Workbench::LargeUpdateEnd() { if (--largeUpdates == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(true); // workbenchContextSupport.setProcessing(true); // Perform window-specific blocking. std::vector windows = this->GetWorkbenchWindows(); for (unsigned int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } void Workbench::OpenFirstTimeWindow() { try { IAdaptable* input; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { input = this->GetDefaultPageInput(); // }}); this->BusyOpenWorkbenchWindow(this->GetPerspectiveRegistry()->GetDefaultPerspective(), input); } catch (WorkbenchException& e) { // Don't use the window's shell as the dialog parent, // as the window is not open yet (bug 76724). //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Problems_Opening_Page, e.getMessage(), e // .getStatus()); // }}); BERRY_ERROR << "Error: Problems opening page. " << e.displayText() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } WorkbenchAdvisor* Workbench::GetAdvisor() { return advisor; } IViewRegistry* Workbench::GetViewRegistry() { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } IEditorRegistry* Workbench::GetEditorRegistry() { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() { return WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry(); } bool Workbench::Close() { return this->Close(PlatformUI::RETURN_OK, false); } bool Workbench::Close(int returnCode, bool force) { - std::cout << "Closing workbench..." << std::endl; + BERRY_INFO << "Closing workbench..."; this->returnCode = returnCode; bool ret; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(force); // } //}); return ret; } /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool Workbench::BusyClose(bool force) { // notify the advisor of preShutdown and allow it to veto if not forced isClosing = advisor->PreShutdown(); if (!force && !isClosing) { return false; } // notify regular workbench clients of preShutdown and allow them to // veto if not forced isClosing = this->FirePreShutdown(force); if (!force && !isClosing) { return false; } // save any open editors if they are dirty isClosing = this->SaveAllEditors(!force); if (!force && !isClosing) { return false; } bool closeEditors = !force && false; // false is the default for the not yet implemented preference below // && PrefUtil.getAPIPreferenceStore().getBoolean( // IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT); if (closeEditors) { // SafeRunner.run(new SafeRunnable() { // public void run() { std::vector windows = this->GetWorkbenchWindows(); for (unsigned int i = 0; i < windows.size(); i++) { IWorkbenchPage::Pointer page = windows[i]->GetActivePage(); if (page) isClosing = isClosing && page->CloseAllEditors(false); } // } //}); if (!force && !isClosing) { return false; } } if (this->GetWorkbenchConfigurer()->GetSaveAndRestore()) { try { // SafeRunner.run(new SafeRunnable() { // public void run() { XMLMemento::Pointer mem = RecordWorkbenchState(); // Save the IMemento to a file. SaveMementoToFile(mem); // } } catch(const Poco::Exception& e) { // public void handleException(Throwable e) { std::string message; if (e.message().empty()) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = "An error has occurred: " + e.message() + ". See error log for more details. Do you want to exit?"; } if (!MessageDialog::OpenQuestion(Shell::Pointer(0), "Error", message)) { isClosing = false; } } // } // }); } if (!force && !isClosing) { return false; } //SafeRunner.run(new SafeRunnable(WorkbenchMessages.ErrorClosing) { // public void run() { if (isClosing || force) { isClosing = windowManager.Close(); } // } //}); if (!force && !isClosing) { return false; } this->Shutdown(); display->ExitEventLoop(0); return true; } bool Workbench::GetWorkbenchStateFile(Poco::File& file) { Poco::Path path; if (!WorkbenchPlugin::GetDefault()->GetDataPath(path)) { return false; } path.append(DEFAULT_WORKBENCH_STATE_FILENAME); file = path; return true; } /* * Save the workbench UI in a persistence file. */ bool Workbench::SaveMementoToFile(XMLMemento::Pointer memento) { // Save it to a file. // XXX: nobody currently checks the return value of this method. Poco::File stateFile; if (!GetWorkbenchStateFile(stateFile)) { return false; } - BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; + //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.path()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { stateFile.remove(); MessageDialog::OpenError(Shell::Pointer(0), "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } std::size_t Workbench::GetWorkbenchWindowCount() { return windowManager.GetWindowCount(); } std::vector Workbench::GetWorkbenchWindows() { std::vector windows = windowManager.GetWindows(); std::vector result; for (std::vector::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const std::string& perspID, IAdaptable* input) { // Run op in busy cursor. //final Object[] result = new Object[1]; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { return this->BusyOpenWorkbenchWindow(perspID, input); // } catch (WorkbenchException e) { // result[0] = e; // } // } //}); } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow(IAdaptable* input) { return this->OpenWorkbenchWindow(this->GetPerspectiveRegistry() ->GetDefaultPerspective(), input); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const std::string& perspectiveId, IWorkbenchWindow::Pointer window) { // If the specified window has the requested perspective open, then the // window // is given focus and the perspective is shown. The page's input is // ignored. WorkbenchWindow::Pointer win = window.Cast (); if (win) { IWorkbenchPage::Pointer page = win->GetActivePage(); if (page) { std::vector perspectives(page ->GetOpenPerspectives()); for (std::size_t i = 0; i < perspectives.size(); i++) { IPerspectiveDescriptor::Pointer persp = perspectives[i]; if (perspectiveId == persp->GetId()) { win->MakeVisible(); page->SetPerspective(persp); return page; } } } } // If another window that has the workspace root as input and the // requested // perpective open and active, then the window is given focus. IAdaptable* input = GetDefaultPageInput(); std::vector windows(GetWorkbenchWindows()); for (std::size_t i = 0; i < windows.size(); i++) { win = windows[i].Cast(); if (window != win) { WorkbenchPage::Pointer page = win->GetActivePage().Cast(); if (page) { bool inputSame = false; if (input == 0) { inputSame = (page->GetInput() == 0); } else { inputSame = input == page->GetInput(); } if (inputSame) { Perspective::Pointer persp = page->GetActivePerspective(); if (persp) { IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc) { if (perspectiveId == desc->GetId()) { Shell::Pointer shell = win->GetShell(); shell->Open(); if (shell->GetMinimized()) { shell->SetMinimized(false); } return page; } } } } } } } // Otherwise the requested perspective is opened and shown in the // specified // window or in a new window depending on the current user preference // for opening // perspectives, and that window is given focus. win = window.Cast(); if (win) { IPreferencesService::Pointer store = WorkbenchPlugin::GetDefault() ->GetPreferencesService(); int mode = store->GetSystemPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = win->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page) { persp = page->GetPerspective(); } // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp) { IWorkbenchWindow::Pointer newWindow = OpenWorkbenchWindow(perspectiveId, input); return newWindow->GetActivePage(); } IPerspectiveDescriptor::Pointer desc = GetPerspectiveRegistry() ->FindPerspectiveWithId(perspectiveId); if (desc == 0) { throw WorkbenchException( "Unable to create perspective \"" + perspectiveId + "\". There is no corresponding perspective extension."); } win->GetShell()->Open(); if (page == 0) { page = win->OpenPage(perspectiveId, input); } else { page->SetPerspective(desc); } return page; } // Just throw an exception.... throw WorkbenchException("Problems opening perspective \"" + perspectiveId + "\""); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const std::string& /*perspectiveId*/, IWorkbenchWindow::Pointer /*window*/, IAdaptable* /*input*/) { return IWorkbenchPage::Pointer(0); // // If the specified window has the requested perspective open and the // // same requested // // input, then the window is given focus and the perspective is shown. // bool inputSameAsWindow = false; // WorkbenchWindow::Pointer win = window.Cast(); // if (win.IsNotNull()) { // WorkbenchPage::Pointer page = win->GetActiveWorkbenchPage(); // if (page.IsNotNull()) { // bool inputSame = false; // if (input == 0) { // inputSame = (page->GetInput() == 0); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // inputSameAsWindow = true; // IPerspectiveDescriptor perspectives[] = page // .getOpenPerspectives(); // for (int i = 0; i < perspectives.length; i++) { // IPerspectiveDescriptor persp = perspectives[i]; // if (perspectiveId.equals(persp.getId())) { // win.makeVisible(); // page.setPerspective(persp); // return page; // } // } // } // } // } // // // If another window has the requested input and the requested // // perpective open and active, then that window is given focus. // IWorkbenchWindow[] windows = getWorkbenchWindows(); // for (int i = 0; i < windows.length; i++) { // win = (WorkbenchWindow) windows[i]; // if (window != win) { // WorkbenchPage page = win.getActiveWorkbenchPage(); // if (page != null) { // boolean inputSame = false; // if (input == null) { // inputSame = (page.getInput() == null); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // Perspective persp = page.getActivePerspective(); // if (persp != null) { // IPerspectiveDescriptor desc = persp.getDesc(); // if (desc != null) { // if (perspectiveId.equals(desc.getId())) { // win.getShell().open(); // return page; // } // } // } // } // } // } // } // // // If the specified window has the same requested input but not the // // requested // // perspective, then the window is given focus and the perspective is // // opened and shown // // on condition that the user preference is not to open perspectives in // // a new window. // win = (WorkbenchWindow) window; // if (inputSameAsWindow && win != null) { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int mode = store.getInt(IPreferenceConstants.OPEN_PERSP_MODE); // // if (IPreferenceConstants.OPM_NEW_WINDOW != mode) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // If the specified window has no active perspective, then open the // // requested perspective and show the specified window. // if (win != null) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor persp = null; // if (page != null) { // persp = page.getPerspective(); // } // if (persp == null) { // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // Otherwise the requested perspective is opened and shown in a new // // window, and the // // window is given focus. // IWorkbenchWindow newWindow = openWorkbenchWindow(perspectiveId, input); // return newWindow.getActivePage(); } bool Workbench::SaveAllEditors(bool /*confirm*/) { return true; } IIntroManager* Workbench::GetIntroManager() { return GetWorkbenchIntroManager(); } WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() { if (introManager == 0) { introManager = new WorkbenchIntroManager(this); } return introManager; } IntroDescriptor::Pointer Workbench::GetIntroDescriptor() const { return introDescriptor; } void Workbench::SetIntroDescriptor(IntroDescriptor::Pointer descriptor) { if (GetIntroManager()->GetIntro()) { GetIntroManager()->CloseIntro(GetIntroManager()->GetIntro()); } introDescriptor = descriptor; } bool Workbench::IsRunning() { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } bool Workbench::IsStarting() { return isStarting; } bool Workbench::IsClosing() { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() { return activatedWindow; } /* * Sets the workbench window which was last known being the active one, or * null . */ void Workbench::SetActivatedWindow(WorkbenchWindow::Pointer window) { activatedWindow = window; } WorkbenchWindow::Pointer Workbench::NewWorkbenchWindow() { WorkbenchWindow::Pointer wbw = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateWorkbenchWindow(this->GetNewWindowNumber()); //wbw->Init(); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. std::vector windows = windowManager.GetWindows(); int count = static_cast(windows.size()); // Create an array of booleans (size = window count). // Cross off every number found in the window list. bool *checkArray = new bool[count]; for (int nX = 0; nX < count; ++nX) { if (windows[nX].Cast ().IsNotNull()) { WorkbenchWindow::Pointer ww = windows[nX].Cast (); int index = ww->GetNumber() - 1; if (index >= 0 && index < count) { checkArray[index] = true; } } } // Return first index which is not used. // If no empty index was found then every slot is full. // Return next index. for (int index = 0; index < count; index++) { if (!checkArray[index]) { delete[] checkArray; return index + 1; } } delete[] checkArray; return static_cast(count + 1); } IWorkbenchWindow::Pointer Workbench::BusyOpenWorkbenchWindow( const std::string& perspID, IAdaptable* input) { // Create a workbench window (becomes active window) //final WorkbenchWindow newWindowArray[] = new WorkbenchWindow[1]; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { // newWindowArray[0] = newWorkbenchWindow(); WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); // } //}); //final WorkbenchWindow newWindow = newWindowArray[0]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Create(); // must be created before adding to window // manager // } //}); windowManager.Add(newWindow); //final WorkbenchException [] exceptions = new WorkbenchException[1]; // Create the initial page. if (perspID != "") { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { try { newWindow->BusyOpenPage(perspID, input); } catch (WorkbenchException& e) { windowManager.Remove(newWindow); throw e; } } // Open window after opening page, to avoid flicker. //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Open(); // } //}); return newWindow; } bool Workbench::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Workbench_problemsSaving, null); bool result = true; // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING[0]); // Save how many plug-ins were loaded while restoring the workbench if (progressCount != -1) { memento->PutInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, progressCount); } // Save the advisor state. IMemento::Pointer advisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); //result.add(getAdvisor().saveState(advisorState)); result &= GetAdvisor()->SaveState(advisorState); // Save the workbench windows. std::vector windows(GetWorkbenchWindows()); for (std::size_t nX = 0; nX < windows.size(); nX++) { WorkbenchWindow::Pointer window = windows[nX].Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_WINDOW); //result.merge(window.saveState(childMem)); result &= window->SaveState(childMem); } // result.add(getEditorHistory().saveState( // memento.createChild(IWorkbenchConstants.TAG_MRU_LIST))); return result; } XMLMemento::Pointer Workbench::RecordWorkbenchState() { XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_WORKBENCH); //final IStatus status = saveState(memento); bool status = SaveState(memento); //if (status.getSeverity() != IStatus.OK) { if (!status) { // // don't use newWindow as parent because it has not yet been opened // // (bug 76724) // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Workbench_problemsSaving, // WorkbenchMessages.Workbench_problemsSavingMsg, status); // }}); } return memento; } void Workbench::AddWorkbenchListener(IWorkbenchListener::Pointer listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener::Pointer listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener::Pointer l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener::Pointer l) { windowEvents.RemoveListener(l); } IWindowListener::Events& Workbench::GetWindowEvents() { return windowEvents; } bool Workbench::FirePreShutdown(bool forced) { //SafeRunnable.run(new SafeRunnable() { // public void run() { typedef IWorkbenchListener::Events::PreShutdownEvent::ListenerList ListenerList; const ListenerList& listeners = workbenchEvents.preShutdown.GetListeners(); for ( ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter ) { // notify each listener if (! (*iter)->Execute(dynamic_cast(this), forced)) return false; } // } return true; } /** * Fire workbench postShutdown event. * * @since 3.2 */ void Workbench::FirePostShutdown() { // SafeRunnable.run(new SafeRunnable() { // public void run() { workbenchEvents.postShutdown(this); // } } void Workbench::FireWindowOpened(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowOpened(window); // } } void Workbench::FireWindowClosed(IWorkbenchWindow::Pointer window) { if (activatedWindow == window) { // Do not hang onto it so it can be GC'ed activatedWindow = 0; } // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowClosed(window); // } } void Workbench::FireWindowActivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowActivated(window); // } } void Workbench::FireWindowDeactivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowDeactivated(window); // } } IWorkbenchWindow::Pointer Workbench::RestoreWorkbenchWindow(IMemento::Pointer memento) { WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); //newWindow.create(); windowManager.Add(newWindow); // whether the window was opened bool opened = false; try { newWindow->RestoreState(memento, IPerspectiveDescriptor::Pointer(0)); newWindow->FireWindowRestored(); newWindow->Open(); opened = true; } catch (...) { if (!opened) { newWindow->Close(); } } return newWindow; } void Workbench::Shutdown() { // shutdown application-specific portions first advisor->PostShutdown(); // notify regular workbench clients of shutdown, and clear the list when // done this->FirePostShutdown(); //workbenchListeners.clear(); //cancelEarlyStartup(); // for dynamic UI // Platform.getExtensionRegistry().removeRegistryChangeListener( // extensionEventHandler); // Platform.getExtensionRegistry().removeRegistryChangeListener( // startupRegistryListener); // ((GrabFocus) Tweaklets.get(GrabFocus.KEY)).dispose(); // Bring down all of the services. // serviceLocator.dispose(); // workbenchActivitySupport.dispose(); // WorkbenchHelpSystem.disposeIfNecessary(); // shutdown the rest of the workbench // WorkbenchColors.shutdown(); // activityHelper.shutdown(); // uninitializeImages(); // if (WorkbenchPlugin.getDefault() != null) { // WorkbenchPlugin.getDefault().reset(); // } // WorkbenchThemeManager.getInstance().dispose(); // PropertyPageContributorManager.getManager().dispose(); // ObjectActionContributorManager.getManager().dispose(); // if (tracker != null) { // tracker.close(); // } Tweaklets::Clear(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp index d3aee3a3c2..05fab16d53 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp @@ -1,1779 +1,1779 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchWindow.h" #include "../berryIWorkbenchPage.h" #include "../berryIPerspectiveDescriptor.h" #include "../berryUIException.h" #include "../berryConstants.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartSite.h" #include "berryIServiceLocatorCreator.h" #include "../tweaklets/berryGuiWidgetsTweaklet.h" #include "../tweaklets/berryWorkbenchTweaklet.h" #include "../services/berryIServiceFactory.h" #include "../berryPlatformUI.h" #include "../berryDebugUtil.h" namespace berry { const int WorkbenchWindow::FILL_ALL_ACTION_BARS = ActionBarAdvisor::FILL_MENU_BAR | ActionBarAdvisor::FILL_COOL_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), 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::Pointer slc = workbench->GetService(IServiceLocatorCreator::GetManifestName()).Cast< IServiceLocatorCreator> (); IServiceLocator::Pointer locator(workbench); this->serviceLocator = slc->CreateServiceLocator(IServiceLocator::WeakPtr( locator), IServiceFactory::ConstPointer(0), IDisposable::WeakPtr( serviceLocatorOwner)).Cast (); // initializeDefaultServices(); // Add contribution managers that are exposed to other plugins. //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()"; + //BERRY_INFO << "WorkbenchWindow::~WorkbenchWindow()"; } Object::Pointer WorkbenchWindow::GetService(const std::string& key) { return serviceLocator->GetService(key); } bool WorkbenchWindow::HasService(const std::string& key) const { return serviceLocator->HasService(key); } Shell::Pointer WorkbenchWindow::GetShell() { 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::Pointer l) { perspectiveEvents.AddListener(l); } void WorkbenchWindow::RemovePerspectiveListener(IPerspectiveListener::Pointer 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 std::string& 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 std::string& 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(int flags) { // Workbench workbench = getWorkbenchImpl(); // workbench.largeUpdateStart(); //try { this->GetActionBarAdvisor()->FillActionBars(flags); // final IMenuService menuService = (IMenuService) serviceLocator // .getService(IMenuService.class); // menuService.populateContributionManager( // (ContributionManager) getActionBars().getMenuManager(), // MenuUtil.MAIN_MENU); // ICoolBarManager coolbar = getActionBars().getCoolBarManager(); // if (coolbar != null) { // menuService.populateContributionManager( // (ContributionManager) coolbar, // MenuUtil.MAIN_TOOLBAR); // } // // } finally { // workbench.largeUpdateEnd(); // } } Point WorkbenchWindow::GetInitialSize() { return this->GetWindowConfigurer()->GetInitialSize(); } bool WorkbenchWindow::Close() { - BERRY_INFO << "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(); } } IWorkbenchPage::Pointer WorkbenchWindow::GetActivePage() { return pageList.GetActive(); } IWorkbench* WorkbenchWindow::GetWorkbench() { return PlatformUI::GetWorkbench(); } IPartService* WorkbenchWindow::GetPartService() { return &partService; } ISelectionService* WorkbenchWindow::GetSelectionService() { return partService.GetSelectionService(); } bool WorkbenchWindow::IsClosing() { return closing || this->GetWorkbenchImpl()->IsClosing(); } int WorkbenchWindow::Open() { if (pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } this->FireWindowCreated(); this->GetWindowAdvisor()->OpenIntro(); int result = Window::Open(); // It's time for a layout ... to insure that if TrimLayout // is in play, it updates all of the trim it's responsible // for. We have to do this before updating in order to get // the PerspectiveBar management correct...see defect 137334 //getShell().layout(); this->FireWindowOpened(); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.updatePerspectiveBar(); // perspectiveSwitcher.updateBarParent(); // } return result; } void* WorkbenchWindow::GetPageComposite() { return pageComposite; } void* WorkbenchWindow::CreateContents(Shell::Pointer parent) { // we know from Window.create that the parent is a Shell. this->GetWindowAdvisor()->CreateWindowContents(parent); // the page composite must be set by createWindowContents poco_assert(pageComposite != 0) ; // "createWindowContents must call configurer.createPageComposite"); //$NON-NLS-1$ return pageComposite; } void WorkbenchWindow::CreateDefaultContents(Shell::Pointer shell) { //pageComposite = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDefaultWindowContents(shell); this->CreatePageComposite(shell->GetControl()); } bool WorkbenchWindow::UnableToRestorePage(IMemento::Pointer pageMem) { std::string pageName; pageMem->GetString(WorkbenchConstants::TAG_LABEL, pageName); // return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.WorkbenchWindow_unableToRestorePerspective, // pageName), null); WorkbenchPlugin::Log("Unable to restore perspective: " + pageName); return false; } bool WorkbenchWindow::RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor) { //TODO WorkbenchWindow restore state poco_assert(GetShell()); // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsRestoringWindow, null); bool result = true; // Restore the window advisor state. IMemento::Pointer windowAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); if (windowAdvisorState) { //result.add(getWindowAdvisor().restoreState(windowAdvisorState)); result &= GetWindowAdvisor()->RestoreState(windowAdvisorState); } // Restore actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); if (actionBarAdvisorState) { // result.add(getActionBarAdvisor() // .restoreState(actionBarAdvisorState)); result &= GetActionBarAdvisor() ->RestoreState(actionBarAdvisorState); } // Read window's bounds and state. Rectangle displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); Rectangle shellBounds; // final IMemento fastViewMem = memento // .getChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewMem != null) { // if (fastViewBar != null) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // fastViewBar.restoreState(fastViewMem); // }}); // // } // } memento->GetInteger(WorkbenchConstants::TAG_X, shellBounds.x); memento->GetInteger(WorkbenchConstants::TAG_Y, shellBounds.y); memento->GetInteger(WorkbenchConstants::TAG_WIDTH, shellBounds.width); memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, shellBounds.height); if (!shellBounds.IsEmpty()) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { if (!shellBounds.Intersects(displayBounds)) { Rectangle clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); shellBounds.x = clientArea.x; shellBounds.y = clientArea.y; } GetShell()->SetBounds(shellBounds); // }}); } std::string maximized; memento->GetString(WorkbenchConstants::TAG_MAXIMIZED, maximized); if (maximized == "true") { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { GetShell()->SetMaximized(true); // }}); } std::string 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; std::vector pageArray = memento ->GetChildren(WorkbenchConstants::TAG_PAGE); for (std::size_t i = 0; i < pageArray.size(); i++) { IMemento::Pointer pageMem = pageArray[i]; std::string strFocus; pageMem->GetString(WorkbenchConstants::TAG_FOCUS, strFocus); if (strFocus.empty()) { continue; } // Get the input factory. IAdaptable* input = 0; IMemento::Pointer inputMem = pageMem->GetChild(WorkbenchConstants::TAG_INPUT); if (inputMem) { std::string factoryID; inputMem->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryID); if (factoryID.empty()) { 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.empty()) { newActivePage = newPage; } } // If there are no pages create a default. if (pageList.IsEmpty()) { try { const std::string defPerspID = this->GetWorkbenchImpl()->GetPerspectiveRegistry() ->GetDefaultPerspective(); if (!defPerspID.empty()) { 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 std::string& 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) { std::string perspId = this->GetWorkbenchImpl()->GetDefaultPerspectiveId(); return this->OpenPage(perspId, input); } IWorkbenchPage::Pointer WorkbenchWindow::BusyOpenPage( const std::string& 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::LargeUpdateStart() { largeUpdates++; } void WorkbenchWindow::LargeUpdateEnd() { if (--largeUpdates == 0) { //TODO WorkbenchWindow update action bars after large update //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); // } //}); } 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() { if (windowConfigurer.IsNull()) { // lazy initialize windowConfigurer = new WorkbenchWindowConfigurer(WorkbenchWindow::Pointer(this)); } return windowConfigurer; } void WorkbenchWindow::ConfigureShell(Shell::Pointer shell) { Window::ConfigureShell(shell); detachedWindowShells = new ShellPool(shell, Constants::TITLE | Constants::MAX | Constants::CLOSE | Constants::RESIZE | Constants::BORDER ); std::string title = this->GetWindowConfigurer()->BasicGetTitle(); if (title != "") { shell->SetText(title); } // final IWorkbench workbench = getWorkbench(); // workbench.getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.WORKBENCH_WINDOW); // final IContextService contextService = (IContextService) getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); this->TrackShellActivation(shell); this->TrackShellResize(shell); } ShellPool::Pointer WorkbenchWindow::GetDetachedWindowPool() { return detachedWindowShells; } WorkbenchAdvisor* WorkbenchWindow::GetAdvisor() { return this->GetWorkbenchImpl()->GetAdvisor(); } WorkbenchWindowAdvisor* WorkbenchWindow::GetWindowAdvisor() { if (windowAdvisor == 0) { windowAdvisor = this->GetAdvisor()->CreateWorkbenchWindowAdvisor(this->GetWindowConfigurer()); poco_check_ptr(windowAdvisor); } return windowAdvisor; } ActionBarAdvisor::Pointer WorkbenchWindow::GetActionBarAdvisor() { if (actionBarAdvisor.IsNull()) { actionBarAdvisor = this->GetWindowAdvisor()->CreateActionBarAdvisor(this->GetWindowConfigurer()->GetActionBarConfigurer()); poco_assert(actionBarAdvisor.IsNotNull()); } return actionBarAdvisor; } Workbench* WorkbenchWindow::GetWorkbenchImpl() { return dynamic_cast(this->GetWorkbench()); } void WorkbenchWindow::ShowEmptyWindowContents() { if (!emptyWindowContentsCreated) { void* parent = this->GetPageComposite(); emptyWindowContents = this->GetWindowAdvisor()->CreateEmptyWindowContents( parent); emptyWindowContentsCreated = true; // // force the empty window composite to be layed out // ((StackLayout) parent.getLayout()).topControl = emptyWindowContents; // parent.layout(); } } void WorkbenchWindow::HideEmptyWindowContents() { if (emptyWindowContentsCreated) { if (emptyWindowContents != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(emptyWindowContents); emptyWindowContents = 0; //this->GetPageComposite().layout(); } emptyWindowContentsCreated = false; } } WorkbenchWindow::ServiceLocatorOwner::ServiceLocatorOwner(WorkbenchWindow* wnd) : window(wnd) { } void WorkbenchWindow::ServiceLocatorOwner::Dispose() { Shell::Pointer shell = window->GetShell(); if (shell != 0) { window->Close(); } } bool WorkbenchWindow::PageList::Add(IWorkbenchPage::Pointer object) { pagesInCreationOrder.push_back(object); pagesInActivationOrder.push_front(object); // It will be moved to top only when activated. return true; } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::Begin() { return pagesInCreationOrder.begin(); } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::End() { return pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Contains(IWorkbenchPage::Pointer object) { return std::find(pagesInCreationOrder.begin(), pagesInCreationOrder.end(), object) != pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Remove(IWorkbenchPage::Pointer object) { if (active == object) { active = 0; } pagesInActivationOrder.remove(object); std::size_t origSize = pagesInCreationOrder.size(); pagesInCreationOrder.remove(object); return origSize != pagesInCreationOrder.size(); } void WorkbenchWindow::PageList::Clear() { pagesInCreationOrder.clear(); pagesInActivationOrder.clear(); active = 0; } bool WorkbenchWindow::PageList::IsEmpty() { return pagesInCreationOrder.empty(); } const std::list& WorkbenchWindow::PageList::GetPages() { return pagesInCreationOrder; } void WorkbenchWindow::PageList::SetActive(IWorkbenchPage::Pointer page) { if (active == page) { return; } active = page; if (page.IsNotNull()) { pagesInActivationOrder.remove(page); pagesInActivationOrder.push_back(page); } } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetActive() { 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); } std::list::reverse_iterator riter = pagesInActivationOrder.rbegin(); return (++riter)->Cast(); } WorkbenchWindow::ShellActivationListener::ShellActivationListener(WorkbenchWindow::Pointer w) : window(w) { } void WorkbenchWindow::ShellActivationListener::ShellActivated(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(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 = new ShellActivationListener(WorkbenchWindow::Pointer(this)); shell->AddShellListener(shellActivationListener); } 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); } }