diff --git a/BlueBerry/Bundles/org.blueberry.compat/berryCTKPluginListener.cpp b/BlueBerry/Bundles/org.blueberry.compat/berryCTKPluginListener.cpp index f7d839eb98..054dc44e7c 100644 --- a/BlueBerry/Bundles/org.blueberry.compat/berryCTKPluginListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.compat/berryCTKPluginListener.cpp @@ -1,162 +1,167 @@ /*========================================================================= 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 "berryCTKPluginListener_p.h" #include +#include + const QString berry::CTKPluginListener::PLUGIN_MANIFEST = "plugin.xml"; namespace berry { CTKPluginListener::CTKPluginListener(IExtensionPointService::Pointer registry) : registry(registry) { } void CTKPluginListener::processPlugins(const QList >& plugins) { // sort the plugins according to their dependencies const QList > sortedPlugins = sortPlugins(plugins); foreach (QSharedPointer plugin, sortedPlugins) { if (isPluginResolved(plugin)) addPlugin(plugin); else removePlugin(plugin); } } QList > CTKPluginListener::sortPlugins(const QList >& plugins) { QList > sortedPlugins(plugins); + QSet installedSymbolicNames; QHash mapPluginIdToDeps; foreach(QSharedPointer plugin, sortedPlugins) { + installedSymbolicNames.insert((plugin->getSymbolicName())); + QString requirePlugin = plugin->getHeaders()[ctkPluginConstants::REQUIRE_PLUGIN]; QStringList requiredList = requirePlugin.split(QRegExp("\\s*,\\s*"), QString::SkipEmptyParts); QStringList requiredSymbolicNames; foreach(QString require, requiredList) { requiredSymbolicNames.append(require.split(';').front()); } mapPluginIdToDeps[plugin->getPluginId()] = requiredSymbolicNames; } - QStringList symbolicNames; + QStringList stableSymbolicNames; for (int i = 0; i < sortedPlugins.size();) { QStringList currDeps = mapPluginIdToDeps[sortedPlugins.at(i)->getPluginId()]; bool moved = false; foreach(QString currDep, currDeps) { - if (!symbolicNames.contains(currDep)) + if (!stableSymbolicNames.contains(currDep) && installedSymbolicNames.contains(currDep)) { sortedPlugins.move(i, sortedPlugins.size()-1); moved = true; break; } } if (!moved) { - symbolicNames.append(sortedPlugins.at(i)->getSymbolicName()); + stableSymbolicNames.append(sortedPlugins.at(i)->getSymbolicName()); ++i; } } return sortedPlugins; } void CTKPluginListener::pluginChanged(const ctkPluginEvent& event) { /* Only should listen for RESOLVED and UNRESOLVED events. * * When a plugin is updated the Framework will publish an UNRESOLVED and * then a RESOLVED event which should cause the plugin to be removed * and then added back into the registry. * * When a plugin is uninstalled the Framework should publish an UNRESOLVED * event and then an UNINSTALLED event so the plugin will have been removed * by the UNRESOLVED event before the UNINSTALLED event is published. */ QSharedPointer plugin = event.getPlugin(); switch (event.getType()) { case ctkPluginEvent::RESOLVED : addPlugin(plugin); break; case ctkPluginEvent::UNRESOLVED : removePlugin(plugin); break; } } bool CTKPluginListener::isPluginResolved(QSharedPointer plugin) { return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0; } void CTKPluginListener::removePlugin(QSharedPointer plugin) { // The BlueBerry extension point registry does not support the removal of contributions //registry->remove(plugin->getPluginId(), timestamp); } QString CTKPluginListener::getExtensionPath(QSharedPointer plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return QString(); // bail out if the plugin does not have a symbolic name if (plugin->getSymbolicName().isEmpty()) return QString(); return PLUGIN_MANIFEST; } void CTKPluginListener::addPlugin(QSharedPointer plugin) { // if the given plugin already exists in the registry then return. // note that this does not work for update cases. std::string contributor = plugin->getSymbolicName().toStdString(); if (registry->HasContributionFrom(contributor)) { return; } QString pluginManifest = getExtensionPath(plugin); if (pluginManifest.isEmpty()) return; QByteArray ba = plugin->getResource(pluginManifest); if (ba.isEmpty()) return; std::string strContent(ba.data()); std::stringbuf strBuf(strContent, std::ios_base::in); std::istream is(&strBuf); registry->AddContribution(is, contributor); } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp index 5b57acb790..0b9a971b19 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp @@ -1,483 +1,486 @@ /*========================================================================= 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 "berryInternalPlatform.h" #include "berryLog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../berryPlatform.h" #include "../berryPlatformException.h" #include "../berryDebugUtil.h" #include "../event/berryPlatformEvents.h" #include "berryPlatformLogChannel.h" #include "../berryIBundle.h" #include "berryCodeCache.h" #include "../berryBundleLoader.h" #include "berrySystemBundle.h" #include "berryBundleDirectory.h" #include "berryProvisioningInfo.h" #include namespace berry { Poco::Mutex InternalPlatform::m_Mutex; InternalPlatform::InternalPlatform() : m_Initialized(false), m_Running(false), m_ConsoleLog(false), m_ServiceRegistry(0), m_CodeCache(0), m_BundleLoader(0), m_SystemBundle(0), m_PlatformLogger(0), m_ctkPluginFrameworkFactory(0), m_EventStarted(PlatformEvent::EV_PLATFORM_STARTED) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { Poco::Mutex::ScopedLock lock(m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } ctkPluginContext* InternalPlatform::GetCTKPluginFrameworkContext() const { if (m_ctkPluginFrameworkFactory) { return m_ctkPluginFrameworkFactory->getFramework()->getPluginContext(); } return 0; } ServiceRegistry& InternalPlatform::GetServiceRegistry() { AssertInitialized(); return *m_ServiceRegistry; } void InternalPlatform::Initialize(int& argc, char** argv, Poco::Util::AbstractConfiguration* config) { // initialization Poco::Mutex::ScopedLock lock(m_Mutex); m_Argc = &argc; m_Argv = argv; try { this->init(argc, argv); } catch (const Poco::Util::UnknownOptionException& e) { BERRY_WARN << e.displayText(); } this->loadConfiguration(); if (config) { this->config().add(config, 50, false); } m_ServiceRegistry = new ServiceRegistry(); m_ConsoleLog = this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG); m_ConfigPath.assign(this->GetConfiguration().getString("application.configDir")); m_InstancePath.assign(this->GetConfiguration().getString("application.dir")); try { m_InstallPath.assign(this->GetConfiguration().getString(Platform::ARG_HOME)); } catch (Poco::NotFoundException& ) { m_InstallPath.assign(m_InstancePath); } m_UserPath.assign(Poco::Path::home()); m_UserPath.pushDirectory("." + this->commandName()); Poco::File userFile(m_UserPath); try { userFile.createDirectory(); userFile.canWrite(); } catch(const Poco::IOException& e) { BERRY_WARN << e.displayText(); m_UserPath.assign(Poco::Path::temp()); m_UserPath.pushDirectory("." + this->commandName()); userFile = m_UserPath; } m_BaseStatePath = m_UserPath; m_BaseStatePath.pushDirectory(".metadata"); m_BaseStatePath.pushDirectory(".plugins"); Poco::Path logPath(m_UserPath); logPath.setFileName(this->commandName() + ".log"); m_PlatformLogChannel = new PlatformLogChannel(logPath.toString()); m_PlatformLogger = &Poco::Logger::create("PlatformLogger", m_PlatformLogChannel, Poco::Message::PRIO_TRACE); try { m_CodeCache = new CodeCache(this->GetConfiguration().getString(Platform::ARG_PLUGIN_CACHE)); } catch (Poco::NotFoundException&) { Poco::Path cachePath(m_UserPath); cachePath.pushDirectory("plugin_cache"); m_CodeCache = new CodeCache(cachePath.toString()); } m_BundleLoader = new BundleLoader(m_CodeCache, *m_PlatformLogger); // Initialize the CTK Plugin Framework ctkProperties fwProps; fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE, QString::fromStdString(userFile.path())); +#if defined(Q_CC_GNU) && ((__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ < 5))) + fwProps.insert(ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS, QVariant::fromValue(QLibrary::ExportExternalSymbolsHint)); +#endif m_ctkPluginFrameworkFactory = new ctkPluginFrameworkFactory(fwProps); QSharedPointer pfw = m_ctkPluginFrameworkFactory->getFramework(); pfw->init(); ctkPluginContext* pfwContext = pfw->getPluginContext(); std::string provisioningFile = this->GetConfiguration().getString(Platform::ARG_PROVISIONING); if (!provisioningFile.empty()) { ProvisioningInfo provInfo(QString::fromStdString(provisioningFile)); foreach(QString pluginPath, provInfo.getPluginDirs()) { ctkPluginFrameworkLauncher::addSearchPath(pluginPath); } QList pluginsToStart = provInfo.getPluginsToStart(); foreach(QUrl pluginUrl, provInfo.getPluginsToInstall()) { QSharedPointer plugin = pfwContext->installPlugin(pluginUrl); if (pluginsToStart.contains(pluginUrl)) { m_CTKPluginsToStart << plugin->getPluginId(); } } } // tell the BundleLoader about the installed CTK plug-ins QStringList installedCTKPlugins; foreach(QSharedPointer plugin, pfwContext->getPlugins()) { installedCTKPlugins << plugin->getSymbolicName(); } m_BundleLoader->SetCTKPlugins(installedCTKPlugins); m_Initialized = true; // Clear the CodeCache if (this->GetConfiguration().hasProperty(Platform::ARG_CLEAN)) m_CodeCache->Clear(); try { // assemble a list of base plugin-directories (which contain // the real plugins as directories) std::vector pluginBaseDirs; Poco::StringTokenizer tokenizer(this->GetConfiguration().getString(Platform::ARG_PLUGIN_DIRS, ""), ";", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); for (Poco::StringTokenizer::Iterator token = tokenizer.begin(); token != tokenizer.end(); ++token) { pluginBaseDirs.push_back(*token); } std::vector pluginPaths; for (std::vector::iterator pluginBaseDir = pluginBaseDirs.begin(); pluginBaseDir != pluginBaseDirs.end(); ++pluginBaseDir) { BERRY_INFO(m_ConsoleLog) << "Plugin base directory: " << *pluginBaseDir; Poco::File pluginDir(*pluginBaseDir); if (!pluginDir.exists() || !pluginDir.isDirectory()) { BERRY_WARN(m_ConsoleLog) << *pluginBaseDir << " is not a direcotry or does not exist. SKIPPED.\n"; continue; } std::vector pluginList; pluginDir.list(pluginList); std::vector::iterator iter; for (iter = pluginList.begin(); iter != pluginList.end(); iter++) { Poco::Path pluginPath = Poco::Path::forDirectory(*pluginBaseDir); pluginPath.pushDirectory(*iter); Poco::File file(pluginPath); if (file.exists() && file.isDirectory()) { pluginPaths.push_back(pluginPath); } } } std::vector::iterator pathIter; for (pathIter = pluginPaths.begin(); pathIter != pluginPaths.end(); pathIter++) { try { Bundle::Pointer bundle = m_BundleLoader->LoadBundle(*pathIter); if (bundle) { BERRY_INFO(m_ConsoleLog) << "Bundle state (" << pathIter->toString() << "): " << bundle->GetStateString() << std::endl; } } catch (const BundleStateException& exc) { BERRY_WARN << exc.displayText() << std::endl; } } // resolve plugins m_BundleLoader->ResolveAllBundles(); } catch (Poco::Exception& exc) { this->logger().log(exc); } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(); #endif } void InternalPlatform::Launch() { AssertInitialized(); if (m_Running) return; m_Running = true; this->run(); } void InternalPlatform::Shutdown() { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); DebugUtil::SaveState(); m_Initialized = false; this->uninitialize(); delete m_ServiceRegistry; delete m_BundleLoader; delete m_CodeCache; } void InternalPlatform::AssertInitialized() { if (!m_Initialized) throw Poco::SystemException("The Platform has not been initialized yet!"); } IExtensionPointService::Pointer InternalPlatform::GetExtensionPointService() { Poco::Mutex::ScopedLock lock(m_Mutex); this->AssertInitialized(); return m_ServiceRegistry->GetServiceById(IExtensionPointService::SERVICE_ID); } const Poco::Path& InternalPlatform::GetConfigurationPath() { return m_ConfigPath; } const Poco::Path& InternalPlatform::GetInstallPath() { return m_InstallPath; } const Poco::Path& InternalPlatform::GetInstancePath() { return m_InstancePath; } bool InternalPlatform::GetStatePath(Poco::Path& statePath, IBundle::Pointer bundle, bool create) { statePath = m_BaseStatePath; statePath.pushDirectory(bundle->GetSymbolicName()); try { Poco::File stateFile(statePath); if (!stateFile.exists() && create) stateFile.createDirectories(); } catch (Poco::FileException&) { return false; } return true; } PlatformEvents& InternalPlatform::GetEvents() { return m_Events; } const Poco::Path& InternalPlatform::GetUserPath() { return m_UserPath; } bool InternalPlatform::IsRunning() const { Poco::Mutex::ScopedLock lock(m_Mutex); return (m_Initialized && m_Running); } IBundle::Pointer InternalPlatform::GetBundle(const std::string& id) { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); return m_BundleLoader->FindBundle(id); } std::vector InternalPlatform::GetBundles() const { return m_BundleLoader->GetBundles(); } Poco::Logger* InternalPlatform::GetLogger() { return m_PlatformLogger; } Poco::Util::LayeredConfiguration& InternalPlatform::GetConfiguration() const { return this->config(); } std::vector InternalPlatform::GetApplicationArgs() const { return m_FilteredArgs; } int& InternalPlatform::GetRawApplicationArgs(char**& argv) { argv = m_Argv; return *m_Argc; } void InternalPlatform::defineOptions(Poco::Util::OptionSet& options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &InternalPlatform::PrintHelp)); options.addOption(helpOption); Poco::Util::Option cleanOption(Platform::ARG_CLEAN, "", "cleans the plugin cache"); cleanOption.binding(Platform::ARG_CLEAN); options.addOption(cleanOption); Poco::Util::Option appOption(Platform::ARG_APPLICATION, "", "the id of the application extension to be executed"); appOption.argument("").binding(Platform::ARG_APPLICATION); options.addOption(appOption); Poco::Util::Option consoleLogOption(Platform::ARG_CONSOLELOG, "", "log messages to the console"); consoleLogOption.binding(Platform::ARG_CONSOLELOG); options.addOption(consoleLogOption); Poco::Util::Option testPluginOption(Platform::ARG_TESTPLUGIN, "", "the plug-in to be tested"); testPluginOption.argument("").binding(Platform::ARG_TESTPLUGIN); options.addOption(testPluginOption); Poco::Util::Option testAppOption(Platform::ARG_TESTAPPLICATION, "", "the application to be tested"); testAppOption.argument("").binding(Platform::ARG_TESTAPPLICATION); options.addOption(testAppOption); Poco::Util::Application::defineOptions(options); } int InternalPlatform::main(const std::vector& args) { m_FilteredArgs = args; m_FilteredArgs.insert(m_FilteredArgs.begin(), this->config().getString("application.argv[0]")); ctkPluginContext* context = GetCTKPluginFrameworkContext(); QFileInfo storageDir = context->getDataFile(""); BundleDirectory::Pointer bundleStorage(new BundleDirectory(Poco::Path(storageDir.absolutePath().toStdString()))); SystemBundle::Pointer systemBundle(new SystemBundle(*m_BundleLoader, bundleStorage)); if (systemBundle == 0) throw PlatformException("Could not find the system bundle"); m_BundleLoader->m_SystemBundle = systemBundle; m_BundleLoader->LoadBundle(systemBundle); m_ctkPluginFrameworkFactory->getFramework()->start(); foreach(long pluginId, m_CTKPluginsToStart) { // do not change the autostart setting of this plugin context->getPlugin(pluginId)->start(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); } m_BundleLoader->StartSystemBundle(systemBundle); systemBundle->Resume(); return EXIT_OK; } void InternalPlatform::PrintHelp(const std::string&, const std::string&) { Poco::Util::HelpFormatter help(this->options()); help.setAutoIndent(); help.setCommand(this->commandName()); help.format(std::cout); exit(EXIT_OK); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml b/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml index 2dedb50602..f6516dcc1d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml @@ -1,68 +1,68 @@ - \ No newline at end of file + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp index 23121d0711..8e65e622d3 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp @@ -1,224 +1,224 @@ /*========================================================================= 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 "berryQtShell.h" #include "berryQtWidgetsTweakletImpl.h" #include "berryQtMainWindowControl.h" #include "berryQtControlWidget.h" #include #include #include #include #include namespace berry { QtShell::QtShell(QWidget* parent, Qt::WindowFlags flags) : updatesDisabled(false) { if (parent == 0 || flags.testFlag(Qt::Window)) { widget = new QtMainWindowControl(this, parent, flags); widget->setUpdatesEnabled(false); updatesDisabled = true; widget->setAttribute(Qt::WA_DeleteOnClose); } else { widget = new QtControlWidget(parent, this, flags | Qt::Dialog); widget->setObjectName("shell widget"); } } QtShell::~QtShell() { widget->deleteLater(); } void QtShell::SetBounds(const Rectangle& bounds) { widget->move(bounds.x, bounds.y); widget->resize(bounds.width, bounds.height); } Rectangle QtShell::GetBounds() const { const QRect& qRect = widget->frameGeometry(); const QSize& size = widget->size(); Rectangle rect(qRect.x(), qRect.y(), size.width(), size.height()); return rect; } void QtShell::SetLocation(int x, int y) { widget->move(x, y); } Point QtShell::ComputeSize(int /*wHint*/, int /*hHint*/, bool changed) { if (changed) widget->updateGeometry(); QSize size(widget->size()); Point point(size.width(), size.height()); return point; } std::string QtShell::GetText() const { return widget->windowTitle().toStdString(); } void QtShell::SetText(const std::string& text) { QString title(QString::fromStdString(text)); widget->setWindowTitle(title); widget->setObjectName(title); } bool QtShell::IsVisible() { return widget->isVisible(); } void QtShell::SetVisible(bool visible) { widget->setVisible(visible); } void QtShell::SetActive() { widget->activateWindow(); widget->raise(); } void* QtShell::GetControl() { return widget; } void QtShell::SetImages(const std::vector& /*images*/) { } bool QtShell::GetMaximized() { return widget->isMaximized(); } bool QtShell::GetMinimized() { return widget->isMinimized(); } void QtShell::SetMaximized(bool maximized) { maximized ? widget->showMaximized() : widget->showNormal(); } void QtShell::SetMinimized(bool minimized) { minimized ? widget->showMinimized() : widget->showNormal(); } void QtShell::AddShellListener(IShellListener::Pointer listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); poco_assert(variant.isValid()); QtWidgetController::Pointer controller = variant.value(); poco_assert(controller != 0); controller->AddShellListener(listener); } void QtShell::RemoveShellListener(IShellListener::Pointer listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); if (controller != 0) controller->RemoveShellListener(listener); } } void QtShell::Open(bool block) { if (updatesDisabled) { widget->setUpdatesEnabled(true); updatesDisabled = false; } widget->setWindowModality(block ? Qt::WindowModal : Qt::NonModal); widget->show(); } void QtShell::Close() { widget->close(); } std::vector QtShell::GetShells() { - GuiWidgetsTweaklet::Pointer widgetTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* widgetTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); std::vector allShells(widgetTweaklet->GetShells()); std::vector descendants; for (std::size_t i = 0; i < allShells.size(); ++i) { Shell::Pointer shell = allShells[i]; if (widgetTweaklet->GetShell(shell->GetControl()) == this) { descendants.push_back(shell); } } return descendants; } int QtShell::GetStyle() { Qt::WindowFlags qtFlags = widget->windowFlags(); int berryFlags = 0; if (!(qtFlags & Qt::FramelessWindowHint)) berryFlags |= Constants::BORDER; if (qtFlags & Qt::WindowTitleHint) berryFlags |= Constants::TITLE; if (qtFlags & Qt::WindowSystemMenuHint) berryFlags |= Constants::CLOSE; if (qtFlags & Qt::WindowMinimizeButtonHint) berryFlags |= Constants::MIN; if (qtFlags & Qt::WindowMaximizeButtonHint) berryFlags |= Constants::MAX; if (widget->windowModality() == Qt::WindowModal) berryFlags |= Constants::PRIMARY_MODAL; else if(widget->windowModality() == Qt::ApplicationModal) berryFlags |= Constants::APPLICATION_MODAL; return berryFlags; } QWidget* QtShell::GetWidget() { return widget; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/berryGeometry.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/berryGeometry.cpp index 9cfa13404a..1b71a8a824 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/berryGeometry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/berryGeometry.cpp @@ -1,172 +1,172 @@ /*========================================================================= 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. =========================================================================*/ // needed under windows to suppress the definition of the // min/max macros in windows.h, which would clash with // std::numeric_limits<>::max() #define NOMINMAX +#include "tweaklets/berryGuiWidgetsTweaklet.h" + #include "berryGeometry.h" #include "berryConstants.h" -#include "tweaklets/berryGuiWidgetsTweaklet.h" - #include namespace berry { int Geometry::GetDimension(const Rectangle& toMeasure, bool width) { if (width) { return toMeasure.width; } return toMeasure.height; } bool Geometry::IsHorizontal(int berrySideConstant) { return !(berrySideConstant == Constants::LEFT || berrySideConstant == Constants::RIGHT); } Rectangle Geometry::GetExtrudedEdge(const Rectangle& toExtrude, int size, int orientation) { Rectangle bounds(toExtrude); if (!IsHorizontal(orientation)) { bounds.width = size; } else { bounds.height = size; } if (orientation == Constants::RIGHT) { bounds.x = toExtrude.x + toExtrude.width - bounds.width; } else if (orientation == Constants::BOTTOM) { bounds.y = toExtrude.y + toExtrude.height - bounds.height; } Normalize(bounds); return bounds; } void Geometry::Normalize(Rectangle& rect) { if (rect.width < 0) { rect.width = -rect.width; rect.x -= rect.width; } if (rect.height < 0) { rect.height = -rect.height; rect.y -= rect.height; } } int Geometry::GetClosestSide(const Rectangle& boundary, const Point& toTest) { int sides[] = { Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM }; int closestSide = Constants::LEFT; int closestDistance = std::numeric_limits::max(); for (unsigned int idx = 0; idx < 4; idx++) { int side = sides[idx]; int distance = GetDistanceFromEdge(boundary, toTest, side); if (distance < closestDistance) { closestDistance = distance; closestSide = side; } } return closestSide; } int Geometry::GetDistanceFromEdge(const Rectangle& rectangle, const Point& testPoint, int edgeOfInterest) { if (edgeOfInterest == Constants::TOP) return testPoint.y - rectangle.y; else if (edgeOfInterest == Constants::BOTTOM) return rectangle.y + rectangle.height - testPoint.y; else if (edgeOfInterest == Constants::LEFT) return testPoint.x - rectangle.x; else if (edgeOfInterest == Constants::RIGHT) return rectangle.x + rectangle.width - testPoint.x; return 0; } int Geometry::GetOppositeSide(int directionConstant) { if (directionConstant == Constants::TOP) return Constants::BOTTOM; else if (directionConstant == Constants::BOTTOM) return Constants::TOP; else if (directionConstant == Constants::LEFT) return Constants::RIGHT; else if (directionConstant == Constants::RIGHT) return Constants::LEFT; return directionConstant; } Rectangle Geometry::ToControl(void* coordinateSystem, const Rectangle& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, toConvert); } Point Geometry::ToControl(void* coordinateSystem, const Point& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(coordinateSystem, toConvert); } Rectangle Geometry::ToDisplay(void* coordinateSystem, const Rectangle& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, toConvert); } Point Geometry::ToDisplay(void* coordinateSystem, const Point& toConvert) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToDisplay(coordinateSystem, toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/berryImageDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/berryImageDescriptor.cpp index 2b9b0caeac..66a27f70c1 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/berryImageDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/berryImageDescriptor.cpp @@ -1,44 +1,44 @@ /*========================================================================= 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 "berryImageDescriptor.h" - #include "tweaklets/berryImageTweaklet.h" +#include "berryImageDescriptor.h" + namespace berry { ImageDescriptor::Pointer ImageDescriptor::CreateFromFile(const std::string& filename, const std::string& pluginid) { return Tweaklets::Get(ImageTweaklet::KEY)->CreateFromFile(filename, pluginid); } ImageDescriptor::Pointer ImageDescriptor::CreateFromImage(void* img) { return Tweaklets::Get(ImageTweaklet::KEY)->CreateFromImage(img); } ImageDescriptor::Pointer ImageDescriptor::GetMissingImageDescriptor() { return Tweaklets::Get(ImageTweaklet::KEY)->GetMissingImageDescriptor(); } ImageDescriptor::ImageDescriptor() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/berryWindow.cpp index ea00ac2a22..8850ca72fb 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::Pointer guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); + 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()"; // // 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/dialogs/berryMessageDialog.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp index 94ce1d14da..2d8e08e7ae 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp @@ -1,67 +1,68 @@ /*========================================================================= 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 "berryMessageDialog.h" #include "../tweaklets/berryMessageDialogTweaklet.h" +#include "berryMessageDialog.h" + namespace berry { bool MessageDialog::OpenConfirm(Shell::Pointer parent, const std::string& title, const std::string& message) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenConfirm(parent, title, message); } void MessageDialog::OpenError(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenError(parent, title, message); } void MessageDialog::OpenInformation(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenInformation(parent, title, message); } bool MessageDialog::OpenQuestion(Shell::Pointer parent, const std::string& title, const std::string& message) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenQuestion(parent, title, message); } void MessageDialog::OpenWarning(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenWarning(parent, title, message); } IDialog::Pointer MessageDialog::CreateMessageDialog(Shell::Pointer parentShell, const std::string& dialogTitle, void* dialogTitleImage, const std::string& dialogMessage, int dialogImageType, const std::vector& dialogButtonLabels, int defaultIndex) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->MessageDialog(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp index f12109bb2e..78895a1045 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp @@ -1,118 +1,118 @@ /*========================================================================= 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 "berryShowViewHandler.h" #include "berryHandlerUtil.h" +#include "../tweaklets/berryWorkbenchTweaklet.h" +#include "../dialogs/berryIShowViewDialog.h" + #include "../berryUIException.h" #include "../berryIWorkbenchPage.h" #include "../berryIViewDescriptor.h" #include "../berryPlatformUI.h" -#include "../tweaklets/berryWorkbenchTweaklet.h" -#include "../dialogs/berryIShowViewDialog.h" - #include #include namespace berry { const std::string ShowViewHandler::PARAMETER_NAME_VIEW_ID = "org.blueberry.ui.showView.viewId"; //$NON-NLS-1$ ShowViewHandler::ShowViewHandler() { } Object::Pointer ShowViewHandler::Execute( const ExecutionEvent::Pointer event) { IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the view identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); ExecutionEvent::ParameterMap::const_iterator result = parameters.find(PARAMETER_NAME_VIEW_ID); std::string value; if (result != parameters.end()) value = result->second; if (value == "") { this->OpenOther(window); } else { try { this->OpenView(value, window); } catch (PartInitException e) { throw ExecutionException("Part could not be initialized", e); //$NON-NLS-1$ } } return Object::Pointer(0); } void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } IShowViewDialog::Pointer dialog = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateStandardDialog(WorkbenchTweaklet::DIALOG_ID_SHOW_VIEW).Cast(); if (dialog.IsNull()) return; int returnCode = dialog->Open(); if (returnCode == IDialog::CANCEL) { return; } const std::vector descriptors = dialog->GetSelection(); for (unsigned int i = 0; i < descriptors.size(); ++i) { try { this->OpenView(descriptors[i]->GetId(), window); } catch (PartInitException e) { // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } void ShowViewHandler::OpenView(const std::string& viewId, IWorkbenchWindow::Pointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp index 898995a80f..7ba4582f03 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp @@ -1,560 +1,561 @@ /*========================================================================= 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 "berryEditorReference.h" +#include "../tweaklets/berryWorkbenchPageTweaklet.h" + #include "berryEditorManager.h" #include "berryEditorDescriptor.h" #include "berryEditorRegistry.h" #include "berryEditorSite.h" #include "berryEditorAreaHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryNullEditorInput.h" #include "berryPartTester.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" #include "../berryImageDescriptor.h" #include "../berryPlatformUI.h" namespace berry { EditorReference::EditorReference(EditorManager* man, IEditorInput::Pointer input, EditorDescriptor::Pointer desc, IMemento::Pointer editorState) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); restoredInput = input; this->editorState = editorState; this->Init(desc->GetId(), "", desc->GetImageDescriptor(), desc->GetLabel(), ""); } EditorReference::EditorReference(EditorManager* man, IMemento::Pointer memento) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); this->editorMemento = memento; if (manager->UseIPersistableEditor()) { //editorState = editorMemento->GetChild(WorkbenchConstants::TAG_EDITOR_STATE); } else { editorState = 0; } // String id = memento.getString(IWorkbenchConstants.TAG_ID); // String title = memento.getString(IWorkbenchConstants.TAG_TITLE); // String tooltip = Util.safeString(memento // .getString(IWorkbenchConstants.TAG_TOOLTIP)); // String partName = memento // .getString(IWorkbenchConstants.TAG_PART_NAME); // // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) // { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) // { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } // For compatibility set the part name to the title if not found // if (partName.empty()) // { // partName = title; // } // Get the editor descriptor. // EditorDescriptor::Pointer desc; // if (id != null) // { // desc = getDescriptor(id); // } // // desc may be null if id is null or desc is not found, but findImage below handles this // String location = memento.getString(IWorkbenchConstants.TAG_PATH); // IPath path = location == null ? null : new Path(location); // ImageDescriptor iDesc = this.manager.findImage(desc, path); // // this.name = memento.getString(IWorkbenchConstants.TAG_NAME); // if (this.name == null) // { // this.name = title; // } // setPinned("true".equals(memento.getString(IWorkbenchConstants.TAG_PINNED))); //$NON-NLS-1$ // // IMemento inputMem = memento.getChild(IWorkbenchConstants.TAG_INPUT); // if (inputMem != null) // { // this.factoryId = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // // init(id, title, tooltip, iDesc, partName, ""); //$NON-NLS-1$ } EditorDescriptor::Pointer EditorReference::GetDescriptor() { return this->GetDescriptor(this->GetId()); } EditorDescriptor::Pointer EditorReference::GetDescriptor(const std::string& id) { EditorDescriptor::Pointer desc; IEditorRegistry* reg = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); desc = reg->FindEditor(id).Cast (); return desc; } void EditorReference::InitListenersAndHandlers() { // Create a property change listener to track the "close editors automatically" // preference and show/remove the pin icon on editors // Only 1 listener will be created in the EditorManager when necessary //this->manager->CheckCreateEditorPropListener(); // Create a keyboard shortcut handler for pinning editors // Only 1 handler will be created in the EditorManager when necessary //this->manager->CheckCreatePinEditorShortcutKeyHandler(); } PartPane::Pointer EditorReference::CreatePane() { PartPane::Pointer pane( new PartPane(IWorkbenchPartReference::Pointer(this), this->manager->page)); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateEditorPane(this, // this->manager->page); } void EditorReference::PinStatusUpdated() { //firePropertyChange(IWorkbenchPart.PROP_TITLE); } std::string EditorReference::GetFactoryId() { // IEditorPart editor = getEditor(false); // if (editor != null) // { // IPersistableElement persistable = editor.getEditorInput() // .getPersistable(); // if (persistable != null) // { // return persistable.getFactoryId(); // } // return null; // } // return factoryId; return ""; } std::string EditorReference::ComputePartName() { return WorkbenchPartReference::ComputePartName(); } std::string EditorReference::GetName() { if (part.IsNotNull()) { return this->GetEditor(false)->GetEditorInput()->GetName(); } return name; } IEditorPart::Pointer EditorReference::GetEditor(bool restore) { return this->GetPart(restore).Cast (); } void EditorReference::SetName(const std::string& name) { this->name = name; } IMemento::Pointer EditorReference::GetMemento() { return editorMemento; } IWorkbenchPage::Pointer EditorReference::GetPage() const { return IWorkbenchPage::Pointer(this->manager->page); } IEditorInput::Pointer EditorReference::GetEditorInput() { IEditorPart::Pointer part = this->GetEditor(false); if (part.IsNotNull()) { return part->GetEditorInput(); } return this->GetRestoredInput(); } IEditorInput::Pointer EditorReference::GetRestoredInput() { if (restoredInput.IsNotNull()) { return restoredInput; } // Get the input factory. // IMemento::Pointer editorMem = this->GetMemento(); // if (editorMem == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_persisted_state, getId(), getName())); // } // IMemento inputMem = editorMem // .getChild(IWorkbenchConstants.TAG_INPUT); // String factoryID = null; // if (inputMem != null) // { // factoryID = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // if (factoryID == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_input_factory_ID, getId(), getName())); // } // IAdaptable input = null; // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.CREATE_PART_INPUT)) // { // label = getName() != null ? getName() : factoryID; // } // try // { // UIStats.start(UIStats.CREATE_PART_INPUT, label); // IElementFactory factory = PlatformUI.getWorkbench() // .getElementFactory(factoryID); // if (factory == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_bad_element_factory, new Object[] // { factoryID, getId(), getName()})); // } // // // Get the input element. // input = factory.createElement(inputMem); // if (input == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_create_element_returned_null, new Object[] // { factoryID, getId(), getName()})); // } // }finally // { // UIStats.end(UIStats.CREATE_PART_INPUT, input, label); // } // if (!(input instanceof IEditorInput)) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_wrong_createElement_result, new Object[] // { factoryID, getId(), getName()})); // } // restoredInput = (IEditorInput) input; return restoredInput; } IWorkbenchPart::Pointer EditorReference::CreatePart() { if (EditorRegistry::EMPTY_EDITOR_ID == this->GetId()) { return this->GetEmptyEditor(this->GetDescriptor()); } IWorkbenchPart::Pointer result; // Try to restore the editor -- this does the real work of restoring the editor // try { result = this->CreatePartHelper().Cast (); } catch (PartInitException e) { // If unable to create the part, create an error part instead // and pass the error to the status handling facility // IStatus originalStatus = exception.getStatus(); // IStatus logStatus = StatusUtil.newStatus(originalStatus, // NLS.bind("Unable to create editor ID {0}: {1}", //$NON-NLS-1$ // getId(), originalStatus.getMessage())); // IStatus displayStatus = StatusUtil.newStatus(originalStatus, // NLS.bind(WorkbenchMessages.EditorManager_unableToCreateEditor, // originalStatus.getMessage())); WorkbenchPlugin::Log("Unable to create editor ID " + this->GetId() + ": " + e.displayText()); // Pass the error to the status handling facility //StatusManager.getManager().handle(logStatus); EditorDescriptor::Pointer descr = this->GetDescriptor(); std::string label = this->GetId(); if (descr.IsNotNull()) label = descr->GetLabel(); IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart(label, e.displayText()); if (part.IsNotNull()) { IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site( new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (...) { //content.dispose(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); WorkbenchPlugin::Log("Error creating editor"); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } } return result; } bool EditorReference::SetInput(IEditorInput::Pointer input) { if (part.IsNotNull()) { if (part.Cast ().IsNotNull()) { IReusableEditor::Pointer editor = part.Cast (); expectingInputChange = true; editor->SetInput(input); // If the editor never fired a PROP_INPUT event, log the fact that we've discovered // a buggy editor and fire the event for free. Firing the event for free isn't required // and cannot be relied on (it only works if the input change was triggered by this // method, and there are definitely other cases where events will still be lost), // but older versions of the workbench did this so we fire it here in the spirit // of playing nice. if (expectingInputChange) { // Log the fact that this editor is broken this->ReportMalfunction( "Editor is not firing a PROP_INPUT event in response to IReusableEditor.setInput(...)"); //$NON-NLS-1$ // Fire the property for free (can't be relied on since there are other ways the input // can change, but we do it here to be consistent with older versions of the workbench) //firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); } return editor->GetEditorInput() == input; } // Can't change the input if the editor already exists and isn't an IReusableEditor return false; } // Changing the input is trivial and always succeeds if the editor doesn't exist yet if (input != restoredInput) { restoredInput = input; //firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); } return true; } void EditorReference::ReportMalfunction(const std::string& string) { if (!reportedMalfunctioningEditor) { reportedMalfunctioningEditor = true; std::string errorMessage = "Problem detected with part " + this->GetId(); //$NON-NLS-1$ if (part.IsNotNull()) { errorMessage.append("(class = ").append(part->GetClassName()).append( ")"); //$NON-NLS-1$ //$NON-NLS-2$ } errorMessage += ": " + string; //$NON-NLS-1$ //StatusManager.getManager().handle(StatusUtil.newStatus(getDescriptor().getPluginId(), errorMessage, null)); BERRY_ERROR << errorMessage << std::endl; } } IEditorPart::Pointer EditorReference::CreatePartHelper() { EditorSite::Pointer site; IEditorPart::Pointer part; try { IEditorInput::Pointer editorInput = this->GetEditorInput(); // Get the editor descriptor. std::string editorID = this->GetId(); EditorDescriptor::Pointer desc = this->GetDescriptor(); if (desc.IsNull()) { throw PartInitException("No editor descriptor for id " + editorID); } if (desc->IsInternal()) { // Create an editor instance. part = manager->CreatePart(desc); this->CreatePartProperties(part); } // else if (desc->GetId() == IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID) // { // // part = ComponentSupport.getSystemInPlaceEditor(); // // if (part == null) // { // throw new PartInitException(WorkbenchMessages.EditorManager_no_in_place_support); // } // } else { throw PartInitException("Invalid editor descriptor for id " + editorID); } // Create a pane for this part PartPane::Pointer pane = this->GetPane(); pane->CreateControl(manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); // Link everything up to the part reference (the part reference itself should not have // been modified until this point) site = manager->CreateSite(IEditorReference::Pointer(this), part, desc, editorInput); // if there is saved state that's appropriate, pass it on if (/*part instanceof IPersistableEditor &&*/editorState.IsNotNull()) { //part->RestoreState(editorState); } // Remember the site and the action bars (now that we've created them, we'll need to dispose // them if an exception occurs) //actionBars = (EditorActionBars) site.getActionBars(); part->CreatePartControl(pane->GetControl()); // The editor should now be fully created. Exercise its public interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave badly, it's much better // that it does so now while we can still cancel creation of the part. PartTester::TestEditor(part); return part; } catch (std::exception e) { throw PartInitException(e.what()); } } IEditorPart::Pointer EditorReference::GetEmptyEditor( EditorDescriptor::Pointer descr) { IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart("(Empty)", ""); IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site(new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (std::exception e) { //StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.what() << std::endl; return IEditorPart::Pointer(0); } this->part = part.Cast (); // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. this->RefreshFromPart(); //this->ReleaseReferences(); if (this->GetPage().Cast ()->GetActiveEditorReference() != this) { //fireInternalPropertyChange(INTERNAL_PROPERTY_OPENED); } return part; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h index 6c04b873a3..a7b82385a6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h @@ -1,82 +1,83 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYERRORVIEWPART_H_ #define BERRYERRORVIEWPART_H_ -#include "../berryViewPart.h" #include "../tweaklets/berryWorkbenchPageTweaklet.h" +#include "../berryViewPart.h" + namespace berry { /** * This part is shown instead the views with errors. * * @since 3.3 */ class ErrorViewPart : public ViewPart { public: berryObjectMacro(ErrorViewPart) /** * Creates instance of the class */ ErrorViewPart(); /** * Creates instance of the class * * @param error the status */ ErrorViewPart(const std::string& title, const std::string& error); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ void CreatePartControl(void* parent); /* * (non-Javadoc) * * @see org.eclipse.ui.part.ViewPart#setPartName(java.lang.String) */ void SetPartName(const std::string& newName); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ void SetFocus(); private: //IStatus error; std::string title; std::string error; Object::Pointer statusPart; }; } #endif /* BERRYERRORVIEWPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp index 5c32e724ae..e8cfd72bb1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp @@ -1,338 +1,338 @@ /*========================================================================= 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 "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryDetachedWindow.h" #include "../tweaklets/berryGuiWidgetsTweaklet.h" #include "../berryIWorkbenchWindow.h" #include "../berryConstants.h" namespace berry { const std::string LayoutPart::PROP_VISIBILITY = "PROP_VISIBILITY"; //$NON-NLS-1$ LayoutPart::LayoutPart(const std::string& id_) : id(id_), deferCount(0) { } LayoutPart::~LayoutPart() { } bool LayoutPart::AllowsAutoFocus() { if (container != 0) { return container->AllowsAutoFocus(); } return true; } void LayoutPart::Dispose() { } Rectangle LayoutPart::GetBounds() { if (this->GetControl() == 0) return Rectangle(); return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetControl()); } ILayoutContainer::Pointer LayoutPart::GetContainer() { return container; } std::string LayoutPart::GetID() const { return id; } bool LayoutPart::IsCompressible() { return false; } Point LayoutPart::GetSize() { Rectangle r = this->GetBounds(); Point ptSize(r.width, r.height); return ptSize; } int LayoutPart::GetSizeFlags(bool /*horizontal*/) { return Constants::MIN; } int LayoutPart::ComputePreferredSize(bool /*width*/, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredParallel) { return preferredParallel; } IDropTarget::Pointer LayoutPart::GetDropTarget(Object::Pointer /*draggedObject*/, const Point& /*displayCoordinates*/) { return IDropTarget::Pointer(0); } bool LayoutPart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer LayoutPart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer LayoutPart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } void LayoutPart::MoveAbove(void* /*refControl*/) { } void LayoutPart::Reparent(void* newParent) { void* control = this->GetControl(); - GuiWidgetsTweaklet::Pointer guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } bool LayoutPart::GetVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl); } return false; } bool LayoutPart::IsVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsVisible(ctrl); } return false; } void LayoutPart::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); if (ctrl != 0) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } // if (!makeVisible && this->IsFocusAncestor(ctrl)) // { // // Workaround for Bug 60970 [EditorMgmt] setActive() called on an editor when it does not have focus. // // Force focus on the shell so that when ctrl is hidden, // // SWT does not try to send focus elsewhere, which may cause // // some other part to be activated, which affects the part // // activation order and can cause flicker. // ctrl.getShell().forceFocus(); // } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(ctrl, makeVisible); } } bool LayoutPart::IsFocusAncestor(void* /*ctrl*/) { // Control f = ctrl.getDisplay().getFocusControl(); // while (f != null && f != ctrl) // { // f = f.getParent(); // } // return f == ctrl; return false; } void LayoutPart::SetBounds(const Rectangle& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } void LayoutPart::SetContainer(ILayoutContainer::Pointer container) { this->container = container; //TODO Zoom // if (container != 0) // { // setZoomed(container.childIsZoomed(this)); // } } void LayoutPart::SetID(const std::string& str) { id = str; } LayoutPart::Pointer LayoutPart::GetPart() { return LayoutPart::Pointer(this); } void LayoutPart::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferringEvents(); } deferCount++; } else { if (deferCount> 0) { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } } void LayoutPart::StartDeferringEvents() { } void LayoutPart::HandleDeferredEvents() { } bool LayoutPart::IsDeferred() { return deferCount> 0; } void LayoutPart::DescribeLayout(std::string& /*buf*/) const { } std::string LayoutPart::GetPlaceHolderId() { return this->GetID(); } void LayoutPart::ResizeChild(LayoutPart::Pointer /*childThatChanged*/) { } void LayoutPart::FlushLayout() { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->ResizeChild(LayoutPart::Pointer(this)); } } bool LayoutPart::AllowsAdd(LayoutPart::Pointer /*toAdd*/) { return false; } std::string LayoutPart::ToString() { return ""; } void LayoutPart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp index 23db3ffd52..8fb22a4a87 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp @@ -1,467 +1,467 @@ /*========================================================================= 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 "berryPartPane.h" +#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "../tweaklets/berryWorkbenchPageTweaklet.h" + #include "berryWorkbenchPage.h" #include "berryPartStack.h" #include "berryEditorAreaHelper.h" #include "berryPerspective.h" #include "berryPartStack.h" #include "berryDragUtil.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" - namespace berry { PartPane::Sashes::Sashes() : left(0), right(0), top(0), bottom(0) { } PartPane::PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage) : StackablePart(partReference->GetId()), control(0), inLayout(true), busy(false), hasFocus(false) { //super(partReference.getId()); this->partReference = partReference; this->page = workbenchPage; } void PartPane::CreateControl(void* parent) { if (this->GetControl() != 0) { return; } partReference.Lock()->AddPropertyListener(IPropertyChangeListener::Pointer(this)); // Create view form. control = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreatePaneControl(parent); // the part should never be visible by default. It will be made visible // by activation. This allows us to have views appear in tabs without // becoming active by default. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(control, false); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(control, 0); // Create a title bar. //this->CreateTitleBar(); // When the pane or any child gains focus, notify the workbench. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(control, GuiTk::IControlListener::Pointer(this)); //control.addTraverseListener(traverseListener); } bool PartPane::IsPlaceHolder() { return false; } PartPane::~PartPane() { // super.dispose(); // this->Register(); if (control != 0) { BERRY_DEBUG << "Deleting PartPane control"; Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(control, GuiTk::IControlListener::Pointer(this)); // control.removeTraverseListener(traverseListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(control); control = 0; } // if ((paneMenuManager != null)) // { // paneMenuManager.dispose(); // paneMenuManager = null; // } // if (!partReference.Expired()) { partReference.Lock()->RemovePropertyListener(IPropertyChangeListener::Pointer(this)); } // partReference.removePartPropertyListener(this); this->UnRegister(false); } void PartPane::DoHide() { if (partReference.Lock().Cast() != 0) { this->GetPage()->HideView(partReference.Lock().Cast()); } else if (partReference.Lock().Cast() != 0) { this->GetPage()->CloseEditor(partReference.Lock().Cast(), true); } } Rectangle PartPane::GetParentBounds() { void* ctrl = this->GetControl(); if (this->GetContainer() != 0 && this->GetContainer().Cast() != 0) { LayoutPart::Pointer part = this->GetContainer().Cast(); if (part->GetControl() != 0) { ctrl = part->GetControl(); } } return DragUtil::GetDisplayBounds(ctrl); } void* PartPane::GetControl() { return control; } IWorkbenchPartReference::Pointer PartPane::GetPartReference() const { return partReference.Lock(); } void PartPane::ControlActivated(GuiTk::ControlEvent::Pointer /*e*/) { if (inLayout) { this->RequestActivation(); } } GuiTk::IControlListener::Events::Types PartPane::GetEventTypes() const { return GuiTk::IControlListener::Events::ACTIVATED; } void PartPane::MoveAbove(void* refControl) { if (this->GetControl() != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(this->GetControl(), refControl); } } void PartPane::RequestActivation() { IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); this->page->RequestActivation(part); } //PartStack::Pointer PartPane::GetStack() //{ // return partStack; //} PartPane::Sashes PartPane::FindSashes() { Sashes result; IStackableContainer::Pointer container = this->GetContainer(); if (container == 0) { return result; } container->FindSashes(result); return result; } WorkbenchPage::Pointer PartPane::GetPage() { return WorkbenchPage::Pointer(page); } void PartPane::SetContainer(IStackableContainer::Pointer container) { if (hasFocus) { IStackableContainer::Pointer oldContainer = this->GetContainer(); if (PartStack::Pointer oldStack = oldContainer.Cast()) { oldStack->SetActive(StackPresentation::AS_INACTIVE); } if (PartStack::Pointer newContainer = container.Cast()) { newContainer->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } } void* containerControl = container == 0 ? 0 : container.Cast()->GetControl(); if (containerControl != 0) { void* control = this->GetControl(); void* newParent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(containerControl); if (control != 0 && newParent != Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(control)) { this->Reparent(newParent); } } StackablePart::SetContainer(container); } void PartPane::Reparent(void* newParent) { void* control = this->GetControl(); - GuiWidgetsTweaklet::Pointer guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void PartPane::ShowFocus(bool inFocus) { if (partReference.Lock().Cast() != 0) { hasFocus = inFocus; } if (PartStack::Pointer stack = this->GetContainer().Cast()) { if (partReference.Lock().Cast() != 0) { stack->SetActive(inFocus ? StackPresentation::AS_ACTIVE_FOCUS : StackPresentation::AS_INACTIVE); } else if (partReference.Lock().Cast() != 0) { if (inFocus) { page->GetEditorPresentation()->SetActiveWorkbook(stack, true); } else { stack->SetActive(page->GetEditorPresentation()->GetActiveWorkbook() == stack ? StackPresentation::AS_ACTIVE_NOFOCUS : StackPresentation::AS_INACTIVE); } } } } PartStack::Pointer PartPane::GetStack() { IStackableContainer::Pointer container = this->GetContainer(); return container.Cast(); } void PartPane::SetVisible(bool makeVisible) { // Avoid redundant visibility changes if (makeVisible == this->GetVisible()) { return; } if (makeVisible) { partReference.Lock()->GetPart(true); } if (this->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(this->GetControl(), makeVisible); partReference.Lock().Cast()->FireVisibilityChange(); } bool PartPane::GetVisible() { if (this->GetControl() != 0) return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(this->GetControl()); return false; } void PartPane::SetFocus() { this->RequestActivation(); IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); if (part.IsNotNull()) { // Control control = getControl(); // if (!SwtUtil.isFocusAncestor(control)) // { // First try to call part.setFocus part->SetFocus(); //} } } void PartPane::SetWorkbenchPage(WorkbenchPage::Pointer workbenchPage) { this->page = workbenchPage.GetPointer(); } void PartPane::DoDock() { // do nothing } void PartPane::SetBusy(bool isBusy) { if (isBusy != busy) { busy = isBusy; //firePropertyChange(IPresentablePart.PROP_BUSY); } } void PartPane::ShowHighlight() { //No nothing by default } void* PartPane::GetToolBar() { return 0; } bool PartPane::HasViewMenu() { return false; } bool PartPane::IsBusy() { return busy; } void PartPane::DescribeLayout(std::string& buf) const { IWorkbenchPartReference::Pointer part = this->GetPartReference(); if (part.IsNotNull()) { buf.append(part->GetPartName()); return; } } bool PartPane::IsCloseable() { if (partReference.Lock().Cast() != 0) { Perspective::Pointer perspective = page->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } return perspective->IsCloseable(partReference.Lock().Cast()); } return true; } void PartPane::SetInLayout(bool inLayout) { this->inLayout = inLayout; } bool PartPane::GetInLayout() { return inLayout; } bool PartPane::AllowsAutoFocus() { if (!inLayout) { return false; } //return super.allowsAutoFocus(); return true; } void PartPane::RemoveContributions() { } void PartPane::AddPropertyListener(IPropertyChangeListener::Pointer listener) { propertyChangeEvents.AddListener(listener); } void PartPane::RemovePropertyListener(IPropertyChangeListener::Pointer listener) { propertyChangeEvents.RemoveListener(listener); } void PartPane::FirePropertyChange(PropertyChangeEvent::Pointer event) { propertyChangeEvents.propertyChange(event); } void PartPane::PropertyChange(PropertyChangeEvent::Pointer event) { this->FirePropertyChange(event); } int PartPane::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return partReference.Lock().Cast()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartPane::GetSizeFlags(bool horizontal) { return partReference.Lock().Cast()->GetSizeFlags(horizontal); } void PartPane::ShellActivated() { } void PartPane::ShellDeactivated() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp index bb86eaee8a..bb1dd25b63 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp @@ -1,1608 +1,1608 @@ /*========================================================================= 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 "berryPartStack.h" #include "berryPerspective.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchPlugin.h" #include "berryPresentationSerializer.h" #include "berryDragUtil.h" #include "berryEditorAreaHelper.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchConstants.h" #include "../berryXMLMemento.h" #include "../berryIWorkbenchPartConstants.h" #include "../berryGeometry.h" #include "../tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { const int PartStack::PROP_SELECTION = 0x42; PartStack::PartStackDropResult::Pointer PartStack::dropResult( new PartStack::PartStackDropResult()); void PartStack::PartStackDropResult::SetTarget(PartStack::Pointer stack, PartPane::Pointer pane, StackDropResult::Pointer result) { this->pane = pane; this->dropResult = result; this->stack = stack; } void PartStack::PartStackDropResult::Drop() { // If we're dragging a pane over itself do nothing //if (dropResult.getInsertionPoint() == pane.getPresentablePart()) { return; }; Object::Pointer cookie; if (dropResult != 0) { cookie = dropResult->GetCookie(); } PartPane::Pointer pane(this->pane); PartStack::Pointer stack(this->stack); // Handle cross window drops by opening a new editor if (pane->GetPartReference().Cast () != 0) { IEditorReference::Pointer editorRef = pane->GetPartReference().Cast< IEditorReference> (); if (pane->GetWorkbenchWindow() != stack->GetWorkbenchWindow()) { try { IEditorInput::Pointer input = editorRef->GetEditorInput(); // Close the old editor and capture the actual closed state incase of a 'cancel' bool editorClosed = pane->GetPage()->CloseEditor(editorRef, true); // Only open open the new editor if the old one closed if (editorClosed) stack->GetPage()->OpenEditor(input, editorRef->GetId()); return; } catch (PartInitException& e) { //e.printStackTrace(); BERRY_ERROR << e.displayText(); } } } if (pane->GetContainer() != stack) { // Moving from another stack stack->DerefPart(pane); pane->Reparent(stack->GetParent()); stack->Add(pane, cookie); stack->SetSelection(pane); pane->SetFocus(); } else if (cookie != 0) { // Rearranging within this stack stack->GetPresentation()->MovePart(stack->GetPresentablePart(pane), cookie); } } DnDTweaklet::CursorType PartStack::PartStackDropResult::GetCursor() { return DnDTweaklet::CURSOR_CENTER; } Rectangle PartStack::PartStackDropResult::GetSnapRectangle() { if (dropResult == 0) { return DragUtil::GetDisplayBounds(stack.Lock()->GetControl()); } return dropResult->GetSnapRectangle(); } PartStack::MyStackPresentationSite::MyStackPresentationSite(PartStack* stack) : partStack(stack) { } void PartStack::MyStackPresentationSite::Close(IPresentablePart::Pointer part) { partStack->Close(part); } void PartStack::MyStackPresentationSite::Close(const std::vector< IPresentablePart::Pointer>& parts) { partStack->Close(parts); } void PartStack::MyStackPresentationSite::DragStart( IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard) { partStack->DragStart(beingDragged, initialLocation, keyboard); } void PartStack::MyStackPresentationSite::DragStart(Point& initialLocation, bool keyboard) { partStack->DragStart(IPresentablePart::Pointer(0), initialLocation, keyboard); } bool PartStack::MyStackPresentationSite::IsPartMoveable( IPresentablePart::Pointer part) { return partStack->IsMoveable(part); } void PartStack::MyStackPresentationSite::SelectPart( IPresentablePart::Pointer toSelect) { partStack->PresentationSelectionChanged(toSelect); } bool PartStack::MyStackPresentationSite::SupportsState(int state) { return partStack->SupportsState(state); } void PartStack::MyStackPresentationSite::SetState(int newState) { partStack->SetState(newState); } IPresentablePart::Pointer PartStack::MyStackPresentationSite::GetSelectedPart() { return partStack->GetSelectedPart(); } // void AddSystemActions(IMenuManager menuManager) { // PartStack.this.addSystemActions(menuManager); // } bool PartStack::MyStackPresentationSite::IsStackMoveable() { return partStack->CanMoveFolder(); } void PartStack::MyStackPresentationSite::FlushLayout() { partStack->FlushLayout(); } PartStack::PresentableVector PartStack::MyStackPresentationSite::GetPartList() { return partStack->GetPresentableParts(); } std::string PartStack::MyStackPresentationSite::GetProperty( const std::string& id) { return partStack->GetProperty(id); } PartStack::PartStack(WorkbenchPage* p, bool allowsStateChanges, int appear, IPresentationFactory* fac) : LayoutPart("PartStack"), page(p), isActive(true), allowStateChanges( allowsStateChanges), appearance(appear), ignoreSelectionChanges(false), factory(fac) { std::stringstream buf; buf << "PartStack@" << this; this->SetID(buf.str()); presentationSite = new MyStackPresentationSite(this); } bool PartStack::IsMoveable(IPresentablePart::Pointer part) { PartPane::Pointer pane = this->GetPaneFor(part); Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } IWorkbenchPartReference::Pointer partRef = pane->GetPartReference(); if (partRef.Cast () != 0) return perspective->IsMoveable(partRef.Cast ()); return true; } bool PartStack::SupportsState(int /*newState*/) { if (page->IsFixedLayout()) { return false; } return allowStateChanges; } bool PartStack::CanMoveFolder() { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) return true; Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return false; } // We need to search if one of the presentations is not moveable // if that's the case the whole folder should not be moveable IStackPresentationSite::Pointer presenationSite; if ((presenationSite = this->GetPresentationSite()) != 0) { std::list parts = presenationSite->GetPartList(); for (std::list::iterator iter = parts.begin(); iter != parts.end(); ++iter) { if (!presenationSite->IsPartMoveable(*iter)) { return false; } } } return !perspective->IsFixedLayout(); } void PartStack::DerefPart(StackablePart::Pointer toDeref) { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) EditorAreaHelper::DerefPart(toDeref); else this->GetPage()->GetActivePerspective()->GetPresentation()->DerefPart( toDeref); } bool PartStack::AllowsDrop(PartPane::Pointer part) { PartStack::Pointer stack = part->GetContainer().Cast (); if (stack != 0) { if (stack->appearance == this->appearance) return true; } return false; } void PartStack::AddListener(IPropertyChangeListener::Pointer listener) { propEvents.AddListener(listener); } void PartStack::RemoveListener(IPropertyChangeListener::Pointer listener) { propEvents.RemoveListener(listener); } int PartStack::GetAppearance() const { return appearance; } std::string PartStack::GetID() const { return LayoutPart::GetID(); } bool PartStack::IsStandalone() { return (appearance == PresentationFactoryUtil::ROLE_STANDALONE || appearance == PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE); } IPresentablePart::Pointer PartStack::GetSelectedPart() { return presentationCurrent.Cast (); } IStackPresentationSite::Pointer PartStack::GetPresentationSite() { return presentationSite; } void PartStack::TestInvariants() { void* focusControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetFocusControl(); bool currentFound = false; ChildVector children = this->GetChildren(); for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer child = *iter; // No 0 children allowed poco_assert(child != 0) ; // "0 children are not allowed in PartStack" // Ensure that all the PartPanes have an associated presentable part IPresentablePart::Pointer part = this->GetPresentablePart(child); if (!child->IsPlaceHolder()) { poco_assert(part != 0); // "All PartPanes must have a non-0 IPresentablePart" } // Ensure that the child's backpointer points to this stack IStackableContainer::Pointer childContainer = child->GetContainer(); // Disable tests for placeholders -- PartPlaceholder backpointers don't // obey the usual rules -- they sometimes point to a container placeholder // for this stack instead of the real stack. if (!child->IsPlaceHolder()) { // If the widgetry exists, the child's backpointer must point to us poco_assert(childContainer.GetPointer() == this); // "PartStack has a child that thinks it has a different parent" // If this child has focus, then ensure that it is selected and that we have // the active appearance. if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(child->GetControl(), focusControl)) { poco_assert(child == current); // "The part with focus is not the selected part" // focus check commented out since it fails when focus workaround in LayoutPart.setVisible is not present // Assert.isTrue(getActive() == StackPresentation.AS_ACTIVE_FOCUS); } } // Ensure that "current" points to a valid child if (child == current) { currentFound = true; } // Test the child's internal state child->TestInvariants(); } // If we have at least one child, ensure that the "current" pointer points to one of them if (this->GetPresentableParts().size()> 0) { poco_assert(currentFound); StackPresentation::Pointer presentation = this->GetPresentation(); // If the presentation controls have focus, ensure that we have the active appearance if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(presentation->GetControl(), focusControl)) { poco_assert(this->GetActive() == StackPresentation::AS_ACTIVE_FOCUS); // "The presentation has focus but does not have the active appearance" } } // Check to that we're displaying the zoomed icon iff we're actually maximized //poco_assert((this->GetState() == IStackPresentationSite::STATE_MAXIMIZED) // == (this->GetContainer() != 0 && this->GetContainer()->ChildIsZoomed(this))); } void PartStack::DescribeLayout(std::string& buf) const { int activeState = this->GetActive(); if (activeState == StackPresentation::AS_ACTIVE_FOCUS) { buf.append("active "); //$NON-NLS-1$ } else if (activeState == StackPresentation::AS_ACTIVE_NOFOCUS) { buf.append("active_nofocus "); //$NON-NLS-1$ } buf.append("("); //$NON-NLS-1$ ChildVector children = this->GetChildren(); int visibleChildren = 0; for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer next = *iter; if (!next->IsPlaceHolder()) { if (iter != children.begin()) { buf.append(", "); //$NON-NLS-1$ } if (next == requestedCurrent) { buf.append("*"); //$NON-NLS-1$ } next->DescribeLayout(buf); visibleChildren++; } } buf.append(")"); //$NON-NLS-1$ } void PartStack::Add(StackablePart::Pointer child) { this->Add(child, Object::Pointer(0)); } void PartStack::Add(StackablePart::Pointer newChild, Object::Pointer cookie) { children.push_back(newChild); // Fix for bug 78470: if(newChild->GetContainer().Cast() == 0) { newChild->SetContainer(IStackableContainer::Pointer(this)); } this->ShowPart(newChild, cookie); } bool PartStack::AllowsAdd(StackablePart::Pointer /*toAdd*/) { return !this->IsStandalone(); } bool PartStack::AllowsAutoFocus() { if (presentationSite->GetState() == IStackPresentationSite::STATE_MINIMIZED) { return false; } return LayoutPart::AllowsAutoFocus(); } void PartStack::Close(const std::vector& parts) { for (unsigned int idx = 0; idx < parts.size(); idx++) { IPresentablePart::Pointer part = parts[idx]; this->Close(part); } } void PartStack::Close(IPresentablePart::Pointer part) { if (!presentationSite->IsCloseable(part)) { return; } PartPane::Pointer pane = this->GetPaneFor(part); if (pane != 0) { pane->DoHide(); } } IPresentationFactory* PartStack::GetFactory() { if (factory != 0) { return factory; } return WorkbenchPlugin::GetDefault()->GetPresentationFactory(); } void PartStack::CreateControl(void* parent) { if (this->GetPresentation() != 0) { return; } IPresentationFactory* factory = this->GetFactory(); PresentableVector partList = this->GetPresentableParts(); std::vector partVec(partList.begin(), partList.end()); PresentationSerializer serializer(partVec); StackPresentation::Pointer presentation = PresentationFactoryUtil ::CreatePresentation(factory, appearance, parent, presentationSite, &serializer, savedPresentationState); this->CreateControl(parent, presentation); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveBelow(this->GetControl(), 0); } IDropTarget::Pointer PartStack::GetDropTarget(Object::Pointer draggedObject, const Point& position) { if (draggedObject.Cast() == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer pane = draggedObject.Cast(); if (this->IsStandalone() || !this->AllowsDrop(pane)) { return IDropTarget::Pointer(0); } // Don't allow views to be dragged between windows bool differentWindows = pane->GetWorkbenchWindow() != this->GetWorkbenchWindow(); bool editorDropOK = ((pane->GetPartReference().Cast() != 0) && pane->GetWorkbenchWindow()->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } StackDropResult::Pointer dropResult = this->GetPresentation()->DragOver( this->GetControl(), position); if (dropResult == 0) { return IDropTarget::Pointer(0); } return this->CreateDropTarget(pane, dropResult); } void PartStack::SetBounds(const Rectangle& r) { if (this->GetPresentation() != 0) { this->GetPresentation()->SetBounds(r); } } IDropTarget::Pointer PartStack::CreateDropTarget(PartPane::Pointer pane, StackDropResult::Pointer result) { dropResult->SetTarget(PartStack::Pointer(this), pane, result); return dropResult; } void PartStack::SetActive(bool isActive) { this->isActive = isActive; // Add all visible children to the presentation for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->SetContainer(isActive ? IStackableContainer::Pointer(this) : IStackableContainer::Pointer(0)); } for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } void PartStack::CreateControl(void* /*parent*/, StackPresentation::Pointer presentation) { poco_assert(this->GetPresentation() == 0); if (presentationSite->GetPresentation() != 0) { return; } presentationSite->SetPresentation(presentation); // Add all visible children to the presentation // Use a copy of the current set of children to avoid a ConcurrentModificationException // if a part is added to the same stack while iterating over the children (bug 78470) ChildVector childParts(children); for (ChildVector::iterator iter = childParts.begin(); iter != childParts.end(); ++iter) { this->ShowPart(*iter, Object::Pointer(0)); } if (savedPresentationState != 0) { PresentableVector partList = this->GetPresentableParts(); std::vector partVec(partList.begin(), partList.end()); PresentationSerializer serializer(partVec); presentation->RestoreState(&serializer, savedPresentationState); } //void* ctrl = this->GetPresentation()->GetControl(); //TODO control setData ? //ctrl.setData(this); // We should not have a placeholder selected once we've created the widgetry if (requestedCurrent != 0 && requestedCurrent->IsPlaceHolder()) { requestedCurrent = 0; this->UpdateContainerVisibleTab(); } this->RefreshPresentationSelection(); } void PartStack::SavePresentationState() { if (this->GetPresentation() == 0) { return; } {// Save the presentation's state before disposing it XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_PRESENTATION); memento->PutString(WorkbenchConstants::TAG_ID, this->GetFactory()->GetId()); std::list parts(this->GetPresentableParts()); PresentationSerializer serializer(std::vector(parts.begin(), parts.end())); this->GetPresentation()->SaveState(&serializer, memento); // Store the memento in savedPresentationState savedPresentationState = memento; } } PartStack::~PartStack() { //BERRY_INFO << "DELETING PARTSTACK"; } void PartStack::Dispose() { if (this->GetPresentation() == 0) { return; } this->SavePresentationState(); // for (PresentableVector::iterator iter = presentableParts.begin(); // iter != presentableParts.end(); ++iter) // { // iter->Cast()->Dispose(); // } presentableParts.clear(); presentationCurrent = 0; current = 0; this->FireInternalPropertyChange(PROP_SELECTION); } void PartStack::FindSashes(PartPane::Sashes& sashes) { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } Rectangle PartStack::GetBounds() { if (this->GetPresentation() == 0) { return Rectangle(0, 0, 0, 0); } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl()); } std::list PartStack::GetChildren() const { return children; } void* PartStack::GetControl() { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation == 0) { return 0; } return presentation->GetControl(); } /** * Answer the number of children. */ PartStack::ChildVector::size_type PartStack::GetItemCount() { if (this->GetPresentation() == 0) { return children.size(); } return this->GetPresentableParts().size(); } PartPane::Pointer PartStack::GetPaneFor(IPresentablePart::Pointer part) { if (part == 0 || part.Cast() == 0) { return PartPane::Pointer(0); } return part.Cast()->GetPane(); } void* PartStack::GetParent() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()); } PartStack::PresentableVector PartStack::GetPresentableParts() { return presentableParts; } PresentablePart::Pointer PartStack::GetPresentablePart(StackablePart::Pointer pane) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer part = iter->Cast(); if (part->GetPane() == pane) { return part; } } return PresentablePart::Pointer(0); } StackPresentation::Pointer PartStack::GetPresentation() { return presentationSite->GetPresentation(); } StackablePart::Pointer PartStack::GetSelection() { return current; } void PartStack::PresentationSelectionChanged(IPresentablePart::Pointer newSelection) { // Ignore selection changes that occur as a result of removing a part if (ignoreSelectionChanges) { return; } PartPane::Pointer newPart = this->GetPaneFor(newSelection); // This method should only be called on objects that are already in the layout poco_assert(newPart != 0); if (newPart == requestedCurrent) { return; } this->SetSelection(newPart); if (newPart != 0) { newPart->SetFocus(); } } void PartStack::Remove(StackablePart::Pointer child) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(child); // Need to remove it from the list of children before notifying the presentation // since it may setVisible(false) on the part, leading to a partHidden notification, // during which findView must not find the view being removed. See bug 60039. children.remove(child); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { ignoreSelectionChanges = true; presentableParts.remove(presentablePart); presentation->RemovePart(presentablePart); presentablePart = 0; ignoreSelectionChanges = false; } if (this->GetPresentation() != 0) { child->SetContainer(IStackableContainer::Pointer(0)); } if (child == requestedCurrent) { this->UpdateContainerVisibleTab(); } } void PartStack::Reparent(void* newParent) { void* control = this->GetControl(); - GuiWidgetsTweaklet::Pointer tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (tweaklet->GetParent(control) == newParent) || !tweaklet->IsReparentable(control)) { return; } LayoutPart::Reparent(newParent); for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->Reparent(newParent); } } void PartStack::Replace(StackablePart::Pointer oldChild, StackablePart::Pointer newChild) { ChildVector::iterator loc = std::find(children.begin(), children.end(), oldChild); int idx = 0; int numPlaceholders = 0; //subtract the number of placeholders still existing in the list //before this one - they wont have parts. for (ChildVector::iterator iter = children.begin(); iter != loc; ++iter, ++idx) { if ((*iter)->IsPlaceHolder()) { numPlaceholders++; } } ObjectInt::Pointer cookie(new ObjectInt(idx - numPlaceholders)); children.insert(loc, newChild); this->ShowPart(newChild, cookie); if (oldChild == requestedCurrent && newChild.Cast() != 0) { this->SetSelection(newChild.Cast()); } this->Remove(oldChild); } int PartStack::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return this->GetPresentation()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartStack::GetSizeFlags(bool horizontal) { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { return presentation->GetSizeFlags(horizontal); } return 0; } bool PartStack::RestoreState(IMemento::Pointer memento) { // Read the active tab. std::string activeTabID; memento->GetString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, activeTabID); // Read the page elements. std::vector children = memento->GetChildren(WorkbenchConstants::TAG_PAGE); // Loop through the page elements. for (std::size_t i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; std::string partID; childMem->GetString(WorkbenchConstants::TAG_CONTENT, partID); // Create the part. StackablePart::Pointer part(new PartPlaceholder(partID)); part->SetContainer(IStackableContainer::Pointer(this)); this->Add(part); //1FUN70C: ITPUI:WIN - Shouldn't set Container when not active //part.setContainer(this); if (partID == activeTabID) { this->SetSelection(part); // Mark this as the active part. //current = part; } } //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); int expanded; if (memento->GetInteger(WorkbenchConstants::TAG_EXPANDED, expanded)) { //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { SetState(expanded != IStackPresentationSite::STATE_MINIMIZED ? IStackPresentationSite::STATE_RESTORED : IStackPresentationSite::STATE_MINIMIZED); // } // }); } else { SetState(IStackPresentationSite::STATE_RESTORED); } int appearance; if (memento->GetInteger(WorkbenchConstants::TAG_APPEARANCE, appearance)) { this->appearance = appearance; } // Determine if the presentation has saved any info here savedPresentationState = 0; std::vector presentationMementos(memento ->GetChildren(WorkbenchConstants::TAG_PRESENTATION)); for (std::size_t idx = 0; idx < presentationMementos.size(); idx++) { IMemento::Pointer child = presentationMementos[idx]; std::string id; child->GetString(WorkbenchConstants::TAG_ID, id); if (id == GetFactory()->GetId()) { savedPresentationState = child; break; } } IMemento::Pointer propertiesState = memento->GetChild(WorkbenchConstants::TAG_PROPERTIES); if (propertiesState) { std::vector props(propertiesState->GetChildren(WorkbenchConstants::TAG_PROPERTY)); for (std::size_t i = 0; i < props.size(); i++) { std::string id = props[i]->GetID(); properties.insert(std::make_pair(id, props[i]->GetTextData())); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } void PartStack::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); bool useShortcut = makeVisible || !isActive; if (ctrl != 0 && useShortcut) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } } if (makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } LayoutPart::SetVisible(makeVisible); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentation->SetVisible(makeVisible); } if (!makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(false); } } } bool PartStack::SaveState(IMemento::Pointer memento) { if (GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { // Save the active tab. if (requestedCurrent) { memento->PutString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, requestedCurrent ->GetCompoundId()); } // Write out the presentable parts (in order) Poco::HashSet cachedIds; PartStack::PresentableVector pparts(GetPresentableParts()); for (PartStack::PresentableVector::iterator ppIter = pparts.begin(); ppIter != pparts.end(); ++ppIter) { PresentablePart::Pointer presPart = ppIter->Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_PAGE); PartPane::Pointer part = presPart->GetPane(); std::string tabText = part->GetPartReference()->GetPartName(); childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, presPart->GetPane()->GetPlaceHolderId()); // Cache the id so we don't write it out later cachedIds.insert(presPart->GetPane()->GetPlaceHolderId()); } for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer next = *iter; PartPane::Pointer part; if (part = next.Cast()) { // Have we already written it out? if (cachedIds.find(part->GetPlaceHolderId()) != cachedIds.end()) continue; } IMemento::Pointer childMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); std::string tabText = "LabelNotFound"; if (part) { tabText = part->GetPartReference()->GetPartName(); } childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, next->GetId()); } } // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { memento->PutInteger(WorkbenchConstants::TAG_EXPANDED, presentationSite->GetState()); // } // else // { // memento // .putInteger( // IWorkbenchConstants.TAG_EXPANDED, // (presentationSite.getState() == IStackPresentationSite.STATE_MINIMIZED) ? IStackPresentationSite.STATE_MINIMIZED // : IStackPresentationSite.STATE_RESTORED); // } memento->PutInteger(WorkbenchConstants::TAG_APPEARANCE, appearance); this->SavePresentationState(); if (savedPresentationState) { IMemento::Pointer presentationState = memento ->CreateChild(WorkbenchConstants::TAG_PRESENTATION); presentationState->PutMemento(savedPresentationState); } if (!properties.empty()) { IMemento::Pointer propertiesState = memento->CreateChild(WorkbenchConstants::TAG_PROPERTIES); for (std::map::iterator iterator = properties.begin(); iterator != properties.end(); ++iterator) { if (iterator->second.empty()) continue; IMemento::Pointer prop = propertiesState->CreateChild(WorkbenchConstants::TAG_PROPERTY, iterator->first); prop->PutTextData(iterator->second); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); return true; } WorkbenchPage::Pointer PartStack::GetPage() { // WorkbenchWindow::Pointer window = this->GetWorkbenchWindow().Cast(); // // if (window == 0) // { // return 0; // } // // return window->GetActivePage().Cast(); return WorkbenchPage::Pointer(page); } void PartStack::SetActive(int activeState) { // if (activeState == StackPresentation::AS_ACTIVE_FOCUS && isMinimized) // { // setMinimized(false); // } presentationSite->SetActive(activeState); } int PartStack::GetActive() const { return presentationSite->GetActive(); } void PartStack::SetSelection(StackablePart::Pointer part) { if (part == requestedCurrent) { return; } requestedCurrent = part; this->RefreshPresentationSelection(); } void PartStack::UpdateActions(PresentablePart::Pointer /*current*/) { } void PartStack::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); this->RefreshPresentationSelection(); } void PartStack::RefreshPresentationSelection() { // If deferring UI updates, exit. if (this->IsDeferred()) { return; } // If the presentation is already displaying the desired part, then there's nothing // to do. if (current == requestedCurrent) { return; } StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentationCurrent = this->GetPresentablePart(requestedCurrent); // this->UupdateActions(presentationCurrent); if (presentationCurrent != 0 && presentation != 0) { requestedCurrent->CreateControl(this->GetParent()); - GuiWidgetsTweaklet::Pointer tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if (tweaklet->GetParent(requestedCurrent->GetControl()) != tweaklet->GetParent(this->GetControl())) { requestedCurrent->Reparent(tweaklet->GetParent(this->GetControl())); } presentation->SelectPart(presentationCurrent); } // Update the return value of getVisiblePart current = requestedCurrent; this->FireInternalPropertyChange(PROP_SELECTION); } } int PartStack::GetState() { return presentationSite->GetState(); } void PartStack::SetState(const int newState) { int oldState = presentationSite->GetState(); if (!this->SupportsState(newState) || newState == oldState) { return; } // WorkbenchWindow::Pointer wbw = this->GetPage()->GetWorkbenchWindow().Cast(); // if (wbw == 0 || wbw->GetShell() == 0 || wbw->GetActivePage() == 0) // return; // // WorkbenchPage::Pointer page = wbw->GetActivePage(); // // bool useNewMinMax = Perspective::UseNewMinMax(page->GetActivePerspective()); // // // we have to fiddle with the zoom behavior to satisfy Intro req's // // by usning the old zoom behavior for its stack // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // useNewMinMax = useNewMinMax; // && !this->IsIntroInStack(); // else if (newState == IStackPresentationSite::STATE_RESTORED) // { // PartStack::Pointer maxStack = page->GetActivePerspective()->GetPresentation()->GetMaximizedStack(); // useNewMinMax = useNewMinMax && maxStack == this; // } // // if (useNewMinMax) // { // //StartupThreading.runWithoutExceptions(new StartupRunnable() // // { // // void runWithException() throws Throwable // // { // wbw->GetPageComposite()->SetRedraw(false); // try // { // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartZoom(); // } // else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartUnzoom(); // } // // if (newState == IStackPresentationSite::STATE_MINIMIZED) // { // setMinimized(true); // } // // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // // } // catch (...) // { // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // } // // this->SetPresentationState(newState); // // } // // }); // } // else // { //// bool minimized = (newState == IStackPresentationSite::STATE_MINIMIZED); //// this->SetMinimized(minimized); //// //// if (newState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomIn(); //// } //// else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomOut(); //// //// if (newState == IStackPresentationSite::STATE_MINIMIZED) //// setMinimized(true); //// } // } } void PartStack::ShowPart(StackablePart::Pointer part, Object::Pointer cookie) { if (this->GetPresentation() == 0) { return; } if (part->IsPlaceHolder()) { part->SetContainer(IStackableContainer::Pointer(this)); return; } if (part.Cast() == 0) { WorkbenchPlugin::Log("Incorrect part " + part->GetId() + "contained in a part stack"); return; } PartPane::Pointer pane = part.Cast(); PresentablePart::Pointer presentablePart(new PresentablePart(pane, Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()))); presentableParts.push_back(presentablePart); if (isActive) { part->SetContainer(IStackableContainer::Pointer(this)); // The active part should always be enabled if (part->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(part->GetControl(), true); } presentationSite->GetPresentation()->AddPart(presentablePart, cookie); if (requestedCurrent == 0) { this->SetSelection(pane); } // if (childObscuredByZoom(part)) // { // presentablePart.enableInputs(false); // } } void PartStack::UpdateContainerVisibleTab() { ChildVector parts = this->GetChildren(); if (parts.size() < 1) { this->SetSelection(StackablePart::Pointer(0)); return; } PartPane::Pointer selPart; int topIndex = 0; WorkbenchPage::Pointer page = this->GetPage(); if (page != 0) { std::vector sortedParts = page->GetSortedParts(); for (ChildVector::iterator partIter = parts.begin(); partIter != parts.end(); ++partIter) { if (partIter->Cast() != 0) { IWorkbenchPartReference::Pointer part = partIter->Cast() ->GetPartReference(); int index = static_cast(std::find(sortedParts.begin(), sortedParts.end(), part) - sortedParts.begin()); if (index >= topIndex) { topIndex = index; selPart = partIter->Cast(); } } } } if (selPart == 0) { PresentableVector presentableParts = this->GetPresentableParts(); if (presentableParts.size() != 0) { IPresentablePart::Pointer part = presentableParts.front(); selPart = this->GetPaneFor(part); } } this->SetSelection(selPart); } void PartStack::ShowSystemMenu() { //this->GetPresentation()->ShowSystemMenu(); } void PartStack::ShowPaneMenu() { //this->GetPresentation()->ShowPaneMenu(); } void PartStack::ShowPartList() { this->GetPresentation()->ShowPartList(); } std::vector PartStack::GetTabList(StackablePart::Pointer part) { if (part != 0) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(part); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { return presentation->GetTabList(presentablePart); } } return std::vector(); } void PartStack::DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard) { if (beingDragged == 0) { this->PaneDragStart(PartPane::Pointer(0), initialLocation, keyboard); } else { if (presentationSite->IsPartMoveable(beingDragged)) { PartPane::Pointer pane = this->GetPaneFor(beingDragged); if (pane != 0) { this->PaneDragStart(pane, initialLocation, keyboard); } } } } void PartStack::PaneDragStart(PartPane::Pointer pane, Point& initialLocation, bool keyboard) { if (pane == 0) { if (this->CanMoveFolder()) { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage Rectangle bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); } DragUtil::PerformDrag(Object::Pointer(this), Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } else { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage Rectangle bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect // See bug 100908 bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); } DragUtil::PerformDrag(pane, Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } IMemento::Pointer PartStack::GetSavedPresentationState() { return savedPresentationState; } void PartStack::FireInternalPropertyChange(int id) { ObjectInt::Pointer val(new ObjectInt(id)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); propEvents.propertyChange(event); } std::string PartStack::GetProperty(const std::string& id) { return properties[id]; } void PartStack::SetProperty(const std::string& id, const std::string& value) { if (value == "") { properties.erase(id); } else { properties.insert(std::make_pair(id, value)); } } void PartStack::CopyAppearanceProperties(PartStack::Pointer copyTo) { copyTo->appearance = this->appearance; if (!properties.empty()) { for (std::map::iterator iter = properties.begin(); iter != properties.end(); ++iter) { copyTo->SetProperty(iter->first, iter->second); } } } void PartStack::ResizeChild(StackablePart::Pointer /*childThatChanged*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp index f8dff83130..9f12ed0d71 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp @@ -1,1765 +1,1765 @@ /*========================================================================= 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 "../tweaklets/berryGuiWidgetsTweaklet.h" + #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveExtensionReader.h" #include "berryEditorSashContainer.h" #include "berryPartSite.h" #include "berryViewSite.h" #include "berryEditorAreaHelper.h" #include "intro/berryIntroConstants.h" #include "../dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" - #include "../presentations/berryIStackPresentationSite.h" namespace berry { const std::string Perspective::VERSION_STRING = "0.016"; Perspective::Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page) : descriptor(desc) { this->Init(page); if (desc.IsNotNull()) { this->CreatePresentation(desc); } } Perspective::Perspective(WorkbenchPage::Pointer page) { this->Init(page); } void Perspective::Init(WorkbenchPage::Pointer page) { editorHidden = false; editorAreaState = IStackPresentationSite::STATE_RESTORED; fixed = false; presentation = 0; shouldHideEditorsOnActivate = false; this->page = page.GetPointer(); this->editorArea = page->GetEditorPresentation()->GetLayoutPart(); this->viewFactory = page->GetViewFactory(); } bool Perspective::BringToTop(IViewReference::Pointer ref) { return presentation->BringPartToTop(this->GetPane(ref)); } bool Perspective::ContainsView(IViewPart::Pointer view) { IViewSite::Pointer site = view->GetViewSite(); IViewReference::Pointer ref = this->FindView(site->GetId(), site->GetSecondaryId()); if (ref.IsNull()) { return false; } return (view.Cast() == ref->GetPart(false)); } void Perspective::CreatePresentation(PerspectiveDescriptor::Pointer persp) { if (persp->HasCustomDefinition()) { this->LoadCustomPersp(persp); } else { this->LoadPredefinedPersp(persp); } } Perspective::~Perspective() { // Get rid of presentation. if (presentation == 0) { DisposeViewRefs(); return; } presentation->Deactivate(); // Release each view. std::vector refs(this->GetViewReferences()); for (std::vector::size_type i = 0, length = refs.size(); i < length; i++) { this->GetViewFactory()->ReleaseView(refs[i]); } mapIDtoViewLayoutRec.clear(); } void Perspective::DisposeViewRefs() { if (!memento) { return; } std::vector views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } std::string secondaryId = ViewFactory::ExtractSecondaryId(id); if (!secondaryId.empty()) { id = ViewFactory::ExtractPrimaryId(id); } std::string removed; childMem->GetString(WorkbenchConstants::TAG_REMOVED, removed); if (removed != "true") { IViewReference::Pointer ref = viewFactory->GetView(id, secondaryId); if (ref) { viewFactory->ReleaseView(ref); } } } } IViewReference::Pointer Perspective::FindView(const std::string& viewId) { return this->FindView(viewId, ""); } IViewReference::Pointer Perspective::FindView(const std::string& id, const std::string& secondaryId) { std::vector refs(this->GetViewReferences()); for (unsigned int i = 0; i < refs.size(); i++) { IViewReference::Pointer ref = refs[i]; if (id == ref->GetId() && (secondaryId == ref->GetSecondaryId())) { return ref; } } return IViewReference::Pointer(0); } void* Perspective::GetClientComposite() { return page->GetClientComposite(); } IPerspectiveDescriptor::Pointer Perspective::GetDesc() { return descriptor; } PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref) { return ref.Cast()->GetPane(); } std::vector Perspective::GetPerspectiveShortcuts() { return perspectiveShortcuts; } PerspectiveHelper* Perspective::GetPresentation() const { return presentation; } std::vector Perspective::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* Perspective::GetViewFactory() { return viewFactory; } std::vector Perspective::GetViewReferences() { // Get normal views. if (presentation == 0) { return std::vector(); } std::vector panes; presentation->CollectViewPanes(panes); std::vector result; // List fastViews = (fastViewManager != 0) ? // fastViewManager.getFastViews(0) // : new ArrayList(); // IViewReference[] resultArray = new IViewReference[panes.size() // + fastViews.size()]; // // // Copy fast views. // int nView = 0; // for (int i = 0; i < fastViews.size(); i++) // { // resultArray[nView] = (IViewReference) fastViews.get(i); // ++nView; // } // Copy normal views. for (std::vector::iterator iter = panes.begin(); iter != panes.end(); ++iter) { PartPane::Pointer pane = *iter; result.push_back(pane->GetPartReference().Cast()); } return result; } void Perspective::HideEditorArea() { if (!this->IsEditorAreaVisible()) { return; } // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { // If it's the currently maximized part we have to restore first // if (this->GetPresentation().getMaximizedStack().Cast() != 0) // { // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) this->HideEditorAreaLocal(); //else // this->SetEditorAreaTrimVisibility(false); } else { this->HideEditorAreaLocal(); } editorHidden = true; } void Perspective::HideEditorAreaLocal() { if (editorHolder != 0) { return; } // Replace the editor area with a placeholder so we // know where to put it back on show editor area request. editorHolder = new ContainerPlaceholder(editorArea->GetID()); presentation->GetLayout()->Replace(editorArea, editorHolder); } bool Perspective::HideView(IViewReference::Pointer ref) { // If the view is locked just return. PartPane::Pointer pane = this->GetPane(ref); presentation->RemovePart(pane); // Dispose view if ref count == 0. this->GetViewFactory()->ReleaseView(ref); return true; } bool Perspective::IsEditorAreaVisible() { return !editorHidden; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(IViewReference::Pointer ref, bool create) { ViewLayoutRec::Pointer result = this->GetViewLayoutRec(ViewFactory::GetKey(ref), create); if (result.IsNull() && create==false) { result = this->GetViewLayoutRec(ref->GetId(), false); } return result; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(const std::string& viewId, bool create) { ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[viewId]; if (rec.IsNull() && create) { rec = new ViewLayoutRec(); mapIDtoViewLayoutRec[viewId] = rec; } return rec; } bool Perspective::IsFixedLayout() { //@issue is there a difference between a fixed //layout and a fixed perspective?? If not the API //may need some polish, WorkbenchPage, PageLayout //and Perspective all have isFixed methods. //PageLayout and Perspective have their own fixed //attribute, we are assuming they are always in sync. //WorkbenchPage delegates to the perspective. return fixed; } bool Perspective::IsStandaloneView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->isStandalone; } bool Perspective::GetShowTitleView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->showTitle; } void Perspective::LoadCustomPersp(PerspectiveDescriptor::Pointer persp) { //get the layout from the registry PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); try { IMemento::Pointer memento = perspRegistry->GetCustomPersp(persp->GetId()); // Restore the layout state. // MultiStatus status = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()), // 0); // status.merge(restoreState(memento)); // status.merge(restoreState()); bool okay = true; okay &= this->RestoreState(memento); okay &= this->RestoreState(); if (!okay) { this->UnableToOpenPerspective(persp, "Unable to open perspective: " + persp->GetLabel()); } } //catch (IOException e) //{ // unableToOpenPerspective(persp, 0); //} catch (WorkbenchException& e) { this->UnableToOpenPerspective(persp, e.displayText()); } } void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const std::string& status) { PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin ::GetDefault()->GetPerspectiveRegistry()); perspRegistry->DeletePerspective(persp); // If this is a predefined perspective, we will not be able to delete // the perspective (we wouldn't want to). But make sure to delete the // customized portion. persp->DeleteCustomDefinition(); std::string title = "Restoring problems"; std::string msg = "Unable to read workbench state."; if (status == "") { MessageDialog::OpenError(Shell::Pointer(0), title, msg); } else { //TODO error dialog //ErrorDialog.openError((Shell) 0, title, msg, status); MessageDialog::OpenError(Shell::Pointer(0), title, msg + "\n" + status); } } void Perspective::LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp) { // Create layout engine. IPerspectiveFactory::Pointer factory; try { factory = persp->CreateFactory(); } catch (CoreException& /*e*/) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } /* * IPerspectiveFactory#createFactory() can return 0 */ if (factory == 0) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } // Create layout factory. ViewSashContainer::Pointer container(new ViewSashContainer(page, this->GetClientComposite())); layout = new PageLayout(container, this->GetViewFactory(), editorArea, descriptor); layout->SetFixed(descriptor->GetFixed()); // // add the placeholders for the sticky folders and their contents IPlaceholderFolderLayout::Pointer stickyFolderRight, stickyFolderLeft, stickyFolderTop, stickyFolderBottom; std::vector descs(WorkbenchPlugin::GetDefault() ->GetViewRegistry()->GetStickyViews()); for (std::size_t i = 0; i < descs.size(); i++) { IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i]; std::string id = stickyViewDescriptor->GetId(); int location = stickyViewDescriptor->GetLocation(); if (location == IPageLayout::RIGHT) { if (stickyFolderRight == 0) { stickyFolderRight = layout ->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_RIGHT, IPageLayout::RIGHT, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderRight->AddPlaceholder(id); } else if (location == IPageLayout::LEFT) { if (stickyFolderLeft == 0) { stickyFolderLeft = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_LEFT, IPageLayout::LEFT, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderLeft->AddPlaceholder(id); } else if (location == IPageLayout::TOP) { if (stickyFolderTop == 0) { stickyFolderTop = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_TOP, IPageLayout::TOP, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderTop->AddPlaceholder(id); } else if (location == IPageLayout::BOTTOM) { if (stickyFolderBottom == 0) { stickyFolderBottom = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_BOTTOM, IPageLayout::BOTTOM, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderBottom->AddPlaceholder(id); } //should never be 0 as we've just added the view above IViewLayout::Pointer viewLayout = layout->GetViewLayout(id); viewLayout->SetCloseable(stickyViewDescriptor->IsCloseable()); viewLayout->SetMoveable(stickyViewDescriptor->IsMoveable()); } // Run layout engine. factory->CreateInitialLayout(layout); PerspectiveExtensionReader extender; extender.ExtendLayout(descriptor->GetId(), layout); // Retrieve view layout info stored in the page layout. std::map layoutInfo = layout->GetIDtoViewLayoutRecMap(); mapIDtoViewLayoutRec.insert(layoutInfo.begin(), layoutInfo.end()); //TODO Perspective action sets // Create action sets. //List temp = new ArrayList(); //this->CreateInitialActionSets(temp, layout.getActionSets()); // IContextService service = 0; // if (page != 0) // { // service = (IContextService) page.getWorkbenchWindow().getService( // IContextService.class); // } // try // { // if (service!=0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // for (Iterator iter = temp.iterator(); iter.hasNext();) // { // IActionSetDescriptor descriptor = (IActionSetDescriptor) iter // .next(); // addAlwaysOn(descriptor); // } // }finally // { // if (service!=0) // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // newWizardShortcuts = layout.getNewWizardShortcuts(); // showViewShortcuts = layout.getShowViewShortcuts(); // perspectiveShortcuts = layout.getPerspectiveShortcuts(); // showInPartIds = layout.getShowInPartIds(); // // // Retrieve fast views // if (fastViewManager != 0) // { // ArrayList fastViews = layout.getFastViews(); // for (Iterator fvIter = fastViews.iterator(); fvIter.hasNext();) // { // IViewReference ref = (IViewReference) fvIter.next(); // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, // !fvIter.hasNext()); // } // } // Is the layout fixed fixed = layout->IsFixed(); // Create presentation. presentation = new PerspectiveHelper(page, container, Perspective::Pointer(this)); // Hide editor area if requested by factory if (!layout->IsEditorAreaVisible()) { this->HideEditorArea(); } } void Perspective::OnActivate() { // Update editor area state. if (editorArea->GetControl() != 0) { bool visible = this->IsEditorAreaVisible(); bool inTrim = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; editorArea->SetVisible(visible && !inTrim); } // // Update fast views. // // Make sure the control for the fastviews are created so they can // // be activated. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl == 0) // { // pane.createControl(getClientComposite()); // ctrl = pane.getControl(); // } // ctrl.setEnabled(false); // Remove focus support. // } // } // } // // Set the visibility of all fast view pins // setAllPinsVisible(true); // Trim Stack Support bool useNewMinMax = Perspective::UseNewMinMax(Perspective::Pointer(this)); bool hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == 0); // We have to set the editor area's stack state -before- // activating the presentation since it's used there to determine // size of the resulting stack if (useNewMinMax && !hideEditorArea) { this->RefreshEditorAreaVisibility(); } // Show the layout presentation->Activate(this->GetClientComposite()); // if (useNewMinMax) // { // fastViewManager.activate(); // // // Move any minimized extension stacks to the trim // if (layout != 0) // { // // Turn aimations off // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useAnimations = preferenceStore // .getbool(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS); // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false); // // List minStacks = layout.getMinimizedStacks(); // for (Iterator msIter = minStacks.iterator(); msIter.hasNext();) // { // ViewStack vs = (ViewStack) msIter.next(); // vs.setMinimized(true); // } // // // Restore the animation pref // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations); // // // this is a one-off deal...set during the extension reading // minStacks.clear(); // layout = 0; // } // } // else // { // // Update the FVB only if not using the new min/max // // // WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow(); //// if (wbw != 0) //// { //// ITrimManager tbm = wbw.getTrimManager(); //// if (tbm != 0) //// { //// IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID); //// if (fvb instanceof FastViewBar) //// { //// ((FastViewBar)fvb).update(true); //// } //// } //// } // } // // If we are -not- using the new min/max then ensure that there // // are no stacks in the trim. This can happen when a user switches // // back to the 3.0 presentation... // if (!Perspective.useNewMinMax(this) && fastViewManager != 0) // { // bool stacksWereRestored = fastViewManager.restoreAllTrimStacks(); // setEditorAreaTrimVisibility(false); // // // Restore any 'maximized' view stack since we've restored // // the minimized stacks // if (stacksWereRestored && presentation.getMaximizedStack().Cast() != 0) // { // ViewStack vs = (ViewStack) presentation.getMaximizedStack(); // vs.setPresentationState(IStackPresentationSite.STATE_RESTORED); // presentation.setMaximizedStack(0); // } // } // We hide the editor area -after- the presentation activates if (hideEditorArea) { // We do this here to ensure that createPartControl is called on the // top editor // before it is hidden. See bug 20166. this->HideEditorArea(); shouldHideEditorsOnActivate = false; // // this is an override so it should handle both states // if (useNewMinMax) // setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED); } layout = 0; } void Perspective::OnDeactivate() { presentation->Deactivate(); //setActiveFastView(0); //setAllPinsVisible(false); // // Update fast views. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl != 0) // { // ctrl.setEnabled(true); // Add focus support. // } // } // } // // fastViewManager.deActivate(); // } // // // Ensure that the editor area trim is hidden as well // setEditorAreaTrimVisibility(false); } void Perspective::PartActivated(IWorkbenchPart::Pointer /*activePart*/) { // // If a fastview is open close it. // if (activeFastView != 0 // && activeFastView.getPart(false) != activePart) // { // setActiveFastView(0); // } } void Perspective::PerformedShowIn(const std::string& /*partId*/) { //showInTimes.insert(std::make_pair(partId, new Long(System.currentTimeMillis()))); } bool Perspective::RestoreState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; // Create persp descriptor. descriptor = new PerspectiveDescriptor("", "", PerspectiveDescriptor::Pointer(0)); //result.add(descriptor.restoreState(memento)); result &= descriptor->RestoreState(memento); PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->FindPerspectiveWithId(descriptor->GetId()).Cast(); if (desc) { descriptor = desc; } this->memento = memento; // Add the visible views. std::vector views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); //result.merge(createReferences(views)); result &= this->CreateReferences(views); memento = memento->GetChild(WorkbenchConstants::TAG_FAST_VIEWS); if (memento) { views = memento->GetChildren(WorkbenchConstants::TAG_VIEW); //result.merge(createReferences(views)); result &= this->CreateReferences(views); } return result; } bool Perspective::CreateReferences(const std::vector& views) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringViews, 0); bool result = true; for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } std::string secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.empty()) { id = ViewFactory::ExtractPrimaryId(id); } // Create and open the view. try { std::string rm; childMem->GetString(WorkbenchConstants::TAG_REMOVED, rm); if (rm != "true") { viewFactory->CreateView(id, secondaryId); } } catch (const PartInitException& e) { childMem->PutString(WorkbenchConstants::TAG_REMOVED, "true"); // result.add(StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e)); WorkbenchPlugin::Log(e.displayText(), e); result &= true; } } return result; } bool Perspective::RestoreState() { if (this->memento == 0) { //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; IMemento::Pointer memento = this->memento; this->memento = 0; const IMemento::Pointer boundsMem(memento->GetChild(WorkbenchConstants::TAG_WINDOW)); if (boundsMem) { Rectangle r(0, 0, 0, 0); boundsMem->GetInteger(WorkbenchConstants::TAG_X, r.x); boundsMem->GetInteger(WorkbenchConstants::TAG_Y, r.y); boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, r.height); boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, r.width); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { if (page->GetWorkbenchWindow()->GetActivePage() == 0) { page->GetWorkbenchWindow()->GetShell()->SetBounds(r); } // } // }); } // Create an empty presentation.. PerspectiveHelper* pres; //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { ViewSashContainer::Pointer mainLayout(new ViewSashContainer(page, this->GetClientComposite())); pres = new PerspectiveHelper(page, mainLayout, Perspective::Pointer(this)); // }}); // Read the layout. // result.merge(pres.restoreState(memento // .getChild(IWorkbenchConstants.TAG_LAYOUT))); result &= pres->RestoreState(memento->GetChild(WorkbenchConstants::TAG_LAYOUT)); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // Add the editor workbook. Do not hide it now. pres->ReplacePlaceholderWithPart(editorArea); // }}); // Add the visible views. std::vector views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); std::string secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.empty()) { id = ViewFactory::ExtractPrimaryId(id); } // skip the intro as it is restored higher up in workbench. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } // Create and open the view. IViewReference::Pointer viewRef = viewFactory->GetView(id, secondaryId); WorkbenchPartReference::Pointer ref = viewRef.Cast(); // report error if (ref == 0) { std::string key = ViewFactory::GetKey(id, secondaryId); // result.add(new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, // NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), 0)); WorkbenchPlugin::Log("Could not find view: " + key); continue; } bool willPartBeVisible = pres->WillPartBeVisible(ref->GetId(), secondaryId); if (willPartBeVisible) { IViewPart::Pointer view = ref->GetPart(true).Cast(); if (view) { ViewSite::Pointer site = view->GetSite().Cast(); pres->ReplacePlaceholderWithPart(site->GetPane().Cast()); } } else { pres->ReplacePlaceholderWithPart(ref->GetPane().Cast()); } } // // Load the fast views // if (fastViewManager != 0) // fastViewManager.restoreState(memento, result); // Load the view layout recs std::vector recMementos(memento ->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); for (std::size_t i = 0; i < recMementos.size(); i++) { IMemento::Pointer recMemento = recMementos[i]; std::string compoundId; if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId)) { ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true); std::string closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr); if (WorkbenchConstants::FALSE_VAL == closeablestr) { rec->isCloseable = false; } std::string moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr); if (WorkbenchConstants::FALSE_VAL == moveablestr) { rec->isMoveable = false; } std::string standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr); if (WorkbenchConstants::TRUE_VAL == standalonestr) { rec->isStandalone = true; std::string showstr; recMemento->GetString(WorkbenchConstants::TAG_SHOW_TITLE, showstr); rec->showTitle = WorkbenchConstants::FALSE_VAL != showstr; } } } //final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); try { // one big try block, don't kill me here // // defer context events // if (service != 0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // // HashSet knownActionSetIds = new HashSet(); // // // Load the always on action sets. std::vector actions; // = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // // knownActionSetIds.add(actionSetID); // } // } // // // Load the always off action sets. // actions = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOff(d); // } // }); // knownActionSetIds.add(actionSetID); // } // } // Load "show view actions". actions = memento->GetChildren(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); for (std::size_t x = 0; x < actions.size(); x++) { std::string id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); showViewShortcuts.push_back(id); } // // Load "show in times". // actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // String timeStr = actions[x] // .getString(IWorkbenchConstants.TAG_TIME); // if (id != 0 && timeStr != 0) // { // try // { // long time = Long.parseLong(timeStr); // showInTimes.put(id, new Long(time)); // } // catch (NumberFormatException e) // { // // skip this one // } // } // } // Load "show in parts" from registry, not memento showInPartIds = this->GetShowInIdsFromRegistry(); // // Load "new wizard actions". // actions = memento // .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // newWizardShortcuts = new ArrayList(actions.length); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // newWizardShortcuts.add(id); // } // Load "perspective actions". actions = memento->GetChildren(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); for (std::size_t x = 0; x < actions.size(); x++) { std::string id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); perspectiveShortcuts.push_back(id); } // ArrayList extActionSets = getPerspectiveExtensionActionSets(); // for (int i = 0; i < extActionSets.size(); i++) // { // String actionSetID = (String) extActionSets.get(i); // if (knownActionSetIds.contains(actionSetID)) // { // continue; // } // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // knownActionSetIds.add(d.getId()); // } // } // // Add the visible set of action sets to our knownActionSetIds // // Now go through the registry to ensure we pick up any new action // // sets // // that have been added but not yet considered by this perspective. // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // IActionSetDescriptor[] array = reg.getActionSets(); // int count = array.length; // for (int i = 0; i < count; i++) // { // IActionSetDescriptor desc = array[i]; // if ((!knownActionSetIds.contains(desc.getId())) // && (desc.isInitiallyVisible())) // { // addActionSet(desc); // } // } } catch (...) { // // restart context changes // if (service != 0) // { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // }); // } } // Save presentation. presentation = pres; // Hide the editor area if needed. Need to wait for the // presentation to be fully setup first. int areaVisible = 0; bool areaVisibleExists = memento->GetInteger(WorkbenchConstants::TAG_AREA_VISIBLE, areaVisible); // Rather than hiding the editors now we must wait until after their // controls // are created. This ensures that if an editor is instantiated, // createPartControl // is also called. See bug 20166. shouldHideEditorsOnActivate = (areaVisibleExists && areaVisible == 0); // // Restore the trim state of the editor area // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // Integer trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE); // if (trimStateInt != 0) // { // editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state // editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0; // } // } // restore the fixed state int isFixed = 0; fixed = (memento->GetInteger(WorkbenchConstants::TAG_FIXED, isFixed) && isFixed == 1); return true; } std::vector Perspective::GetShowInIdsFromRegistry() { PerspectiveExtensionReader reader; std::vector tags; tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART); reader.SetIncludeOnlyTags(tags); PageLayout::Pointer layout(new PageLayout()); reader.ExtendLayout(descriptor->GetOriginalId(), layout); return layout->GetShowInPartIds(); } void Perspective::SaveDesc() { this->SaveDescAs(descriptor); } void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer /*desc*/) { //TODO Perspective SaveDescAs // PerspectiveDescriptor::Pointer realDesc = desc.Cast(); // //get the layout from the registry // PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin // ::GetDefault()->GetPerspectiveRegistry()); // // Capture the layout state. // XMLMemento memento = XMLMemento.createWriteRoot("perspective");//$NON-NLS-1$ // IStatus status = saveState(memento, realDesc, false); // if (status.getSeverity() == IStatus.ERR) // { // ErrorDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage, // status); // return; // } // //save it to the preference store // try // { // perspRegistry.saveCustomPersp(realDesc, memento); // descriptor = realDesc; // } // catch (IOException e) // { // perspRegistry.deletePerspective(realDesc); // MessageDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage); // } } bool Perspective::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); // // result.merge(saveState(memento, descriptor, true)); bool result = true; result &= this->SaveState(memento, descriptor, true); return result; } bool Perspective::SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); bool result = true; if (this->memento) { memento->PutMemento(this->memento); return result; } // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING); //result.add(p.saveState(memento)); result &= p->SaveState(memento); if (!saveInnerViewState) { Rectangle bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds()); IMemento::Pointer boundsMem = memento ->CreateChild(WorkbenchConstants::TAG_WINDOW); boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x); boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); } // // Save the "always on" action sets. // Iterator itr = alwaysOnActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // // Save the "always off" action sets. // itr = alwaysOffActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // Save "show view actions" for (std::vector::iterator itr = showViewShortcuts.begin(); itr != showViewShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // // Save "show in times" // itr = showInTimes.keySet().iterator(); // while (itr.hasNext()) // { // String id = (String) itr.next(); // Long time = (Long) showInTimes.get(id); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME); // child.putString(IWorkbenchConstants.TAG_ID, id); // child.putString(IWorkbenchConstants.TAG_TIME, time.toString()); // } // // Save "new wizard actions". // itr = newWizardShortcuts.iterator(); // while (itr.hasNext()) // { // String str = (String) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // child.putString(IWorkbenchConstants.TAG_ID, str); // } // Save "perspective actions". for (std::vector::iterator itr = perspectiveShortcuts.begin(); itr != perspectiveShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // Get visible views. std::vector viewPanes; presentation->CollectViewPanes(viewPanes); // Save the views. for (std::vector::iterator itr = viewPanes.begin(); itr != viewPanes.end(); ++itr) { IWorkbenchPartReference::Pointer ref((*itr)->GetPartReference()); IViewDescriptor::Pointer desc = page->GetViewFactory()->GetViewRegistry() ->Find(ref->GetId()); if(desc && desc->IsRestorable()) { IMemento::Pointer viewMemento = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref.Cast())); } } // // save all fastview state // if (fastViewManager != 0) // fastViewManager.saveState(memento); // Save the view layout recs. for (std::map::iterator i = mapIDtoViewLayoutRec.begin(); i != mapIDtoViewLayoutRec.end(); ++i) { std::string compoundId(i->first); ViewLayoutRec::Pointer rec(i->second); if (rec && (!rec->isCloseable || !rec->isMoveable || rec->isStandalone)) { IMemento::Pointer layoutMemento(memento ->CreateChild(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); layoutMemento->PutString(WorkbenchConstants::TAG_ID, compoundId); if (!rec->isCloseable) { layoutMemento->PutString(WorkbenchConstants::TAG_CLOSEABLE, WorkbenchConstants::FALSE_VAL); } if (!rec->isMoveable) { layoutMemento->PutString(WorkbenchConstants::TAG_MOVEABLE, WorkbenchConstants::FALSE_VAL); } if (rec->isStandalone) { layoutMemento->PutString(WorkbenchConstants::TAG_STANDALONE, WorkbenchConstants::TRUE_VAL); layoutMemento->PutString(WorkbenchConstants::TAG_SHOW_TITLE, rec->showTitle ? WorkbenchConstants::TRUE_VAL : WorkbenchConstants::FALSE_VAL); } } } // Save the layout. IMemento::Pointer childMem(memento->CreateChild(WorkbenchConstants::TAG_LAYOUT)); //result.add(presentation.saveState(childMem)); result &= presentation->SaveState(childMem); // Save the editor visibility state if (this->IsEditorAreaVisible()) { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 0); } // // Save the trim state of the editor area if using the new min/max // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // int trimState = editorAreaState; // trimState |= editorAreaRestoreOnUnzoom ? 4 : 0; // memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState); // } // Save the fixed state if (fixed) { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 0); } return result; } void Perspective::SetPerspectiveActionIds(const std::vector& list) { perspectiveShortcuts = list; } void Perspective::SetShowInPartIds(const std::vector& list) { showInPartIds = list; } void Perspective::SetShowViewActionIds(const std::vector& list) { showViewShortcuts = list; } void Perspective::ShowEditorArea() { if (this->IsEditorAreaVisible()) { return; } editorHidden = false; // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) { // If the editor area is going to show then we have to restore // if (getPresentation().getMaximizedStack() != 0) // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); this->ShowEditorAreaLocal(); } // else // setEditorAreaTrimVisibility(true); } else { this->ShowEditorAreaLocal(); } } void Perspective::ShowEditorAreaLocal() { if (editorHolder == 0 || editorHidden) { return; } // Replace the part holder with the editor area. presentation->GetLayout()->Replace(editorHolder, editorArea); editorHolder = 0; } void Perspective::SetEditorAreaState(int newState) { if (newState == editorAreaState) return; editorAreaState = newState; // // reset the restore flag if we're not minimized // if (newState != IStackPresentationSite::STATE_MINIMIZED) // editorAreaRestoreOnUnzoom = false; this->RefreshEditorAreaVisibility(); } int Perspective::GetEditorAreaState() { return editorAreaState; } void Perspective::RefreshEditorAreaVisibility() { // Nothing shows up if the editor area isn't visible at all if (editorHidden) { this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(false); return; } PartStack::Pointer editorStack = editorArea.Cast()->GetUpperRightEditorStack(); if (editorStack == 0) return; // Whatever we're doing, make the current editor stack match it //editorStack->SetStateLocal(editorAreaState); // If it's minimized then it's in the trim if (editorAreaState == IStackPresentationSite::STATE_MINIMIZED) { // Hide the editor area and show its trim this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(true); } else { // Show the editor area and hide its trim //setEditorAreaTrimVisibility(false); this->ShowEditorAreaLocal(); // if (editorAreaState == IStackPresentationSite::STATE_MAXIMIZED) // getPresentation().setMaximizedStack(editorStack); } } IViewReference::Pointer Perspective::GetViewReference(const std::string& viewId, const std::string& secondaryId) { IViewReference::Pointer ref = page->FindViewReference(viewId, secondaryId); if (ref == 0) { ViewFactory* factory = this->GetViewFactory(); try { ref = factory->CreateView(viewId, secondaryId); } catch (PartInitException& /*e*/) { // IStatus status = StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e); // StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$ // StatusManager.LOG); //TODO Perspective status message WorkbenchPlugin::Log("Failed to create view: id=" + viewId); } } return ref; } IViewPart::Pointer Perspective::ShowView(const std::string& viewId, const std::string& secondaryId) { ViewFactory* factory = this->GetViewFactory(); IViewReference::Pointer ref = factory->CreateView(viewId, secondaryId); IViewPart::Pointer part = ref->GetPart(true).Cast(); if (part == 0) { throw PartInitException("Could not create view: " + ref->GetId()); } PartSite::Pointer site = part->GetSite().Cast(); PartPane::Pointer pane = site->GetPane(); //TODO Perspective preference store // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE); // // if (openViewMode == IPreferenceConstants.OVM_FAST && // fastViewManager != 0) // { // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true); // setActiveFastView(ref); // } // else if (openViewMode == IPreferenceConstants.OVM_FLOAT // && presentation.canDetach()) // { // presentation.addDetachedPart(pane); // } // else // { if (this->UseNewMinMax(Perspective::Pointer(this))) { // Is this view going to show in the trim? // LayoutPart vPart = presentation.findPart(viewId, secondaryId); // Determine if there is a trim stack that should get the view std::string trimId; // // If we can locate the correct trim stack then do so // if (vPart != 0) // { // String id = 0; // ILayoutContainer container = vPart.getContainer(); // if (container.Cast() != 0) // id = ((ContainerPlaceholder)container).getID(); // else if (container.Cast() != 0) // id = ((ViewStack)container).getID(); // // // Is this place-holder in the trim? // if (id != 0 && fastViewManager.getFastViews(id).size()> 0) // { // trimId = id; // } // } // // // No explicit trim found; If we're maximized then we either have to find an // // arbitrary stack... // if (trimId == 0 && presentation.getMaximizedStack() != 0) // { // if (vPart == 0) // { // ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack(); // if (blTrimStack != 0) // { // // OK, we've found a trim stack to add it to... // trimId = blTrimStack.getId(); // // // Since there was no placeholder we have to add one // LayoutPart blPart = presentation.findPart(trimId, 0); // if (blPart.Cast() != 0) // { // ContainerPlaceholder cph = (ContainerPlaceholder) blPart; // if (cph.getRealContainer().Cast() != 0) // { // ViewStack vs = (ViewStack) cph.getRealContainer(); // // // Create a 'compound' id if this is a multi-instance part // String compoundId = ref.getId(); // if (ref.getSecondaryId() != 0) // compoundId = compoundId + ':' + ref.getSecondaryId(); // // // Add the new placeholder // vs.add(new PartPlaceholder(compoundId)); // } // } // } // } // } // // // If we have a trim stack located then add the view to it // if (trimId != "") // { // fastViewManager.addViewReference(trimId, -1, ref, true); // } // else // { // bool inMaximizedStack = vPart != 0 && vPart.getContainer() == presentation.getMaximizedStack(); // Do the default behavior presentation->AddPart(pane); // // Now, if we're maximized then we have to minimize the new stack // if (presentation.getMaximizedStack() != 0 && !inMaximizedStack) // { // vPart = presentation.findPart(viewId, secondaryId); // if (vPart != 0 && vPart.getContainer().Cast() != 0) // { // ViewStack vs = (ViewStack)vPart.getContainer(); // vs.setState(IStackPresentationSite.STATE_MINIMIZED); // // // setting the state to minimized will create the trim toolbar // // so we don't need a 0 pointer check here... // fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true); // } // } // } } else { presentation->AddPart(pane); } //} // Ensure that the newly showing part is enabled if (pane != 0 && pane->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(pane->GetControl(), true); return part; } IWorkbenchPartReference::Pointer Perspective::GetOldPartRef() { return oldPartRef; } void Perspective::SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef) { this->oldPartRef = oldPartRef; } bool Perspective::IsCloseable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isCloseable; } return true; } bool Perspective::IsMoveable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isMoveable; } return true; } void Perspective::DescribeLayout(std::string& buf) const { // std::vector fastViews = getFastViews(); // // if (fastViews.length != 0) // { // buf.append("fastviews ("); //$NON-NLS-1$ // for (int idx = 0; idx < fastViews.length; idx++) // { // IViewReference ref = fastViews[idx]; // // if (idx> 0) // { // buf.append(", "); //$NON-NLS-1$ // } // // buf.append(ref.getPartName()); // } // buf.append("), "); //$NON-NLS-1$ // } this->GetPresentation()->DescribeLayout(buf); } void Perspective::TestInvariants() { this->GetPresentation()->GetLayout()->TestInvariants(); } bool Perspective::UseNewMinMax(Perspective::Pointer activePerspective) { // We need to have an active perspective if (activePerspective == 0) return false; // We need to have a trim manager (if we don't then we // don't create a FastViewManager because it'd be useless) // if (activePerspective->GetFastViewManager() == 0) // return false; // Make sure we don't NPE anyplace WorkbenchWindow::Pointer wbw = activePerspective->page->GetWorkbenchWindow().Cast(); if (wbw == 0) return false; // WorkbenchWindowConfigurer* configurer = wbw->GetWindowConfigurer(); // if (configurer == 0) // return false; IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); if (factory == 0) return false; // Ok, we should be good to go, return the pref //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp index 1d7d96b4f6..65115057d9 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp @@ -1,1673 +1,1674 @@ /*========================================================================= 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 "../tweaklets/berryGuiWidgetsTweaklet.h" + #include "berryPerspectiveHelper.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" #include "berryLayoutTree.h" #include "berryEditorSashContainer.h" #include "berryDragUtil.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchConstants.h" #include #include namespace berry { const int PerspectiveHelper::MIN_DETACH_WIDTH = 150; const int PerspectiveHelper::MIN_DETACH_HEIGHT = 250; PerspectiveHelper::DragOverListener::DragOverListener(PerspectiveHelper* perspHelper) : perspHelper(perspHelper) { } IDropTarget::Pointer PerspectiveHelper::DragOverListener::Drag( void* /*currentControl*/, Object::Pointer draggedObject, const Point& /*position*/, const Rectangle& dragRectangle) { if (draggedObject.Cast() != 0) { PartPane::Pointer part = draggedObject.Cast(); if (part->GetContainer().Cast()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); // Views that haven't been shown yet have no 'control' which causes // 'GetWorkbenchWindow' to return 'null' so check explicitly if (part->GetPage() != perspHelper->page) return IDropTarget::Pointer(0); else if (part->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, part, dragRectangle); else perspHelper->dropTarget->SetTarget(part, dragRectangle); } else if (draggedObject.Cast() != 0) { PartStack::Pointer stack = draggedObject.Cast(); if (stack->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); if (stack->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, stack, dragRectangle); else perspHelper->dropTarget->SetTarget(stack, dragRectangle); } return perspHelper->dropTarget; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartPane::Pointer part, const Rectangle& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, const Rectangle& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const Rectangle& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, const Rectangle& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(stack, dragRectangle); } void PerspectiveHelper::ActualDropTarget::Drop() { if (part != 0) { Shell::Pointer shell = part->GetShell(); if (shell->GetData().Cast () != 0) { // if only one view in tab folder then do a window move IStackableContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { if (container.Cast()->GetItemCount() == 1) { shell->SetLocation(dragRectangle.x, dragRectangle.y); return; } } } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->DetachPart(part, dragRectangle.x, dragRectangle.y); } else if (stack != 0) { Shell::Pointer shell = stack->GetShell(); if (shell->GetData().Cast () != 0) { // only one tab folder in a detach window, so do window // move shell->SetLocation(dragRectangle.x, dragRectangle.y); return; } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->Detach(stack, dragRectangle.x, dragRectangle.y); } } DnDTweaklet::CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { return DnDTweaklet::CURSOR_OFFSCREEN; } PerspectiveHelper::MatchingPart::MatchingPart(const std::string& pid, const std::string& sid, StackablePart::Pointer part) { this->pid = pid; this->sid = sid; this->part = part; this->len = pid.size() + sid.size(); this->hasWildcard = (pid.find_first_of(PartPlaceholder::WILD_CARD) != std::string::npos) || (sid.find_first_of(PartPlaceholder::WILD_CARD) != std::string::npos); } bool PerspectiveHelper::CompareMatchingParts::operator()(const MatchingPart& m1, const MatchingPart& m2) const { // specific ids always outweigh ids with wildcards if (m1.hasWildcard && !m2.hasWildcard) { return true; } if (!m1.hasWildcard && m2.hasWildcard) { return false; } // if both are specific or both have wildcards, simply compare based on length return m1.len > m2.len; } PerspectiveHelper::PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective::Pointer persp) : page(workbenchPage), perspective(persp), mainLayout(mainLayout), detachable(false), active(false) { // Views can be detached if the feature is enabled (true by default, // use the plug-in customization file to disable), and if the platform // supports detaching. this->dragTarget = new DragOverListener(this); //TODO preference store // IPreferenceStore store = PlatformUI.getPreferenceStore(); // this.detachable = store.getBoolean( // IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS); this->detachable = true; if (this->detachable) { // Check if some arbitrary Composite supports reparenting. If it // doesn't, views cannot be detached. void* client = workbenchPage->GetClientComposite(); if (client == 0) { // The workbench page is not initialized. I don't think this can happen, // but if it does, silently set detachable to false. this->detachable = false; } else { this->detachable = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsReparentable(client); } } } void PerspectiveHelper::Activate(void* parent) { if (active) { return; } parentWidget = parent; // Activate main layout // make sure all the views have been properly parented std::vector children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (std::vector::iterator iter = children.begin(); iter != children.end(); ++iter) { PartPane::Pointer part = *iter; part->Reparent(parent); } mainLayout->CreateControl(parent); mainLayout->SetActive(true); // Open the detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Open(); } this->EnableAllDrag(); // // Ensure that the maximized stack's presentation state is correct // if (maximizedStackId != 0) // { // LayoutPart part = this->FindPart(maximizedStackId); // if (part.Cast() != 0) // { // maximizedStack = (PartStack) part; // maximizedStackId = 0; // } // } // // // NOTE: we only handle ViewStacks here; Editor Stacks are handled by the // // perspective // if (maximizedStack instanceof ViewStack) // { // maximizedStack.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } active = true; } void PerspectiveHelper::AddPart(StackablePart::Pointer part) { // Look for a placeholder. PartPlaceholder::Pointer placeholder; StackablePart::Pointer testPart; std::string primaryId = part->GetId(); std::string secondaryId; IViewReference::Pointer ref; if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast (); ref = pane->GetPartReference().Cast (); if (ref != 0) secondaryId = ref->GetSecondaryId(); } if (secondaryId != "") { testPart = this->FindPart(primaryId, secondaryId); } else { testPart = this->FindPart(primaryId); } // validate the testPart if (testPart != 0 && testPart.Cast() != 0) { placeholder = testPart.Cast (); } // If there is no placeholder do a simple add. Otherwise, replace the // placeholder if its not a pattern matching placholder if (placeholder == 0) { part->Reparent(mainLayout->GetParent()); LayoutPart::Pointer relative = mainLayout->FindBottomRight(); if (relative != 0 && relative.Cast() != 0) { IStackableContainer::Pointer stack = relative.Cast (); if (stack->AllowsAdd(part)) { mainLayout->Stack(part, stack); } else { mainLayout->AddPart(part); } } else { mainLayout->AddPart(part); } } else { IStackableContainer::Pointer container = placeholder->GetContainer(); if (container != 0) { if (container.Cast () != 0) { //Create a detached window add the part on it. DetachedPlaceHolder::Pointer holder = container.Cast(); detachedPlaceHolderList.remove(holder); container->Remove(testPart); DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); part->CreateControl(window->GetShell()->GetControl()); // Open window. window->GetShell()->SetBounds(holder->GetBounds()); window->Open(); // add part to detached window. PartPane::Pointer pane = part.Cast(); window->Add(pane); std::list otherChildren = holder->GetChildren(); for (std::list::iterator iter = otherChildren.begin(); iter != otherChildren.end(); ++iter) { part->GetContainer()->Add(*iter); } } else { // show parent if necessary if (container.Cast () != 0) { ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(IStackableContainer::Pointer(0)); } // reparent part. //if (!(container instanceof ViewStack)) // { // We don't need to reparent children of PartTabFolders since they will automatically // reparent their children when they become visible. This if statement used to be // part of an else branch. Investigate if it is still necessary. // part.reparent(mainLayout.getParent()); // } // see if we should replace the placeholder if (placeholder->HasWildCard()) { // if (container instanceof PartSashContainer) // { // ((PartSashContainer) container) .addChildForPlaceholder(part, // placeholder); // } // else // { container->Add(part); // } } else { container->Replace(placeholder, part); } } } } } void PerspectiveHelper::AttachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); // Restore any maximized part before re-attaching. // Note that 'getMaximizedStack != 0' implies 'useNewMinMax' // if (getMaximizedStack() != 0) // { // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } this->DerefPart(pane); this->AddPart(pane); this->BringPartToTop(pane); pane->SetFocus(); } bool PerspectiveHelper::CanDetach() { return detachable; } bool PerspectiveHelper::BringPartToTop(StackablePart::Pointer part) { IStackableContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); if (folder->GetSelection() != part) { folder->SetSelection(part); return true; } } return false; } bool PerspectiveHelper::IsPartVisible(IWorkbenchPartReference::Pointer partRef) { StackablePart::Pointer foundPart; if (partRef.Cast () != 0) { foundPart = this->FindPart(partRef->GetId(), partRef.Cast()->GetSecondaryId()); } else { foundPart = this->FindPart(partRef->GetId()); } if (foundPart == 0) { return false; } if (foundPart.Cast () != 0) { return false; } IStackableContainer::Pointer container = foundPart->GetContainer(); if (container.Cast () != 0) { return false; } if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); StackablePart::Pointer visiblePart = folder->GetSelection(); if (visiblePart == 0) { return false; } return partRef == visiblePart.Cast()->GetPartReference(); } return true; } bool PerspectiveHelper::WillPartBeVisible(const std::string& partId) { return this->WillPartBeVisible(partId, 0); } bool PerspectiveHelper::WillPartBeVisible(const std::string& partId, const std::string& secondaryId) { StackablePart::Pointer part = this->FindPart(partId, secondaryId); if (part == 0) { return false; } IStackableContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { container = container.Cast()->GetRealContainer(); } if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); if (folder->GetSelection() == 0) { return false; } return part->GetCompoundId() == folder->GetSelection().Cast()->GetCompoundId(); } return true; } std::vector PerspectiveHelper::CollectPlaceholders() { // Scan the main window. std::vector results = this->CollectPlaceholders( mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; std::list moreResults = win->GetChildren(); if (moreResults.size()> 0) { for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) results.push_back(iter->Cast()); } } } } return results; } std::vector PerspectiveHelper::CollectPlaceholders( const std::list& parts) { std::vector result; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { // iterate through sub containers to find sub-parts std::vector newParts = this->CollectPlaceholders( part.Cast()->GetChildren()); result.insert(result.end(), newParts.begin(), newParts.end()); } else if (part.Cast () != 0) { std::list children = part.Cast()->GetChildren(); for (std::list::iterator partIter = children.begin(); partIter != children.end(); ++partIter) { if (partIter->Cast() != 0) result.push_back(partIter->Cast()); } } } return result; } std::vector PerspectiveHelper::CollectContainerPlaceholders() { // Scan the main window. std::vector results(this->CollectContainerPlaceholders( mainLayout->GetChildren())); // // Scan each detached window. // if (detachable) // { // for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); // winIter != detachedWindowList.end(); ++winIter) // { // DetachedWindow::Pointer win = *winIter; // std::list moreResults = win->GetChildren(); // if (moreResults.size()> 0) // { // for (std::list::iterator iter = moreResults.begin(); // iter != moreResults.end(); ++iter) // { // if (iter->Cast() != 0) // results.push_back(iter->Cast()); // } // } // } // } return results; } std::vector PerspectiveHelper::CollectContainerPlaceholders( const std::list& parts) { std::vector result; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { // iterate through sub containers to find sub-parts std::vector newParts = this->CollectContainerPlaceholders( part.Cast()->GetChildren()); result.insert(result.end(), newParts.begin(), newParts.end()); } else if (part.Cast () != 0) { result.push_back(part.Cast()); } } return result; } void PerspectiveHelper::CollectViewPanes(std::vector& result) { // Scan the main window. this->CollectViewPanes(result, mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; std::list moreResults = win->GetChildren(); for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) result.push_back(iter->Cast()); } } } } void PerspectiveHelper::CollectViewPanes(std::vector& result, const std::list& parts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0 && part.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { std::list children = part.Cast()->GetChildren(); for (std::list::iterator partIter = children.begin(); partIter != children.end(); ++partIter) { if (partIter->Cast() != 0) result.push_back(partIter->Cast()); } } else if (part.Cast () != 0) { this->CollectViewPanes(result, part.Cast()->GetChildren()); } } } void PerspectiveHelper::Deactivate() { if (!active) { return; } this->DisableAllDrag(); // Reparent all views to the main window void* parent = mainLayout->GetParent(); std::vector children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer window = *winIter; std::list moreResults = window->GetChildren(); for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) children.push_back(iter->Cast()); } } // *** Do we even need to do this if detached windows not supported? for (std::vector::iterator itr = children.begin(); itr != children.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } // Dispose main layout. mainLayout->SetActive(false); // Dispose the detached windows for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Close(); } active = false; } PerspectiveHelper::~PerspectiveHelper() { mainLayout->Dispose(); mainLayout->DisposeSashes(); } void PerspectiveHelper::DescribeLayout(std::string& buf) const { if (detachable) { if (detachedWindowList.size() != 0) { buf.append("detachedWindows ("); //$NON-NLS-1$ for (DetachedWindowsType::const_iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::ConstPointer window = *winIter; std::list children = window->GetChildren(); unsigned int j = 0; if (children.size() != 0) { buf.append("dWindow ("); //$NON-NLS-1$ for (std::list::iterator partIter = children.begin(); partIter != children.end(); ++partIter, ++j) { if (partIter->Cast() != 0) buf.append(partIter->Cast()->GetPlaceHolderId()); else if (partIter->Cast() != 0) buf.append( partIter->Cast()->GetPartReference()->GetPartName()); if (j < (children.size() - 1)) { buf.append(", "); //$NON-NLS-1$ } } buf.append(")"); //$NON-NLS-1$ } } buf.append("), "); //$NON-NLS-1$ } } this->GetLayout()->DescribeLayout(buf); } void PerspectiveHelper::DerefPart(StackablePart::Pointer part) { // if (part.Cast () != 0) // { // IViewReference::Pointer ref = ((ViewPane) part).getViewReference(); // if (perspective.isFastView(ref)) // { // // Special check: if it's a fast view then it's actual ViewStack // // may only contain placeholders and the stack is represented in // // the presentation by a container placeholder...make sure the // // PartPlaceHolder for 'ref' is removed from the ViewStack // String id = perspective.getFastViewManager().getIdForRef(ref); // LayoutPart parentPart = findPart(id, 0); // if (parentPart.Cast () != 0) // { // ViewStack vs = // (ViewStack) ((ContainerPlaceholder) parentPart).getRealContainer(); // std::vector kids = vs.getChildren(); // for (int i = 0; i < kids.length; i++) // { // if (kids[i].Cast () != 0) // { // if (ref.getId().equals(kids[i].id)) // vs.remove(kids[i]); // } // } // } // perspective.getFastViewManager().removeViewReference(ref, true, true); // } // } // Get vital part stats before reparenting. IStackableContainer::Pointer oldContainer = part->GetContainer(); bool wasDocked = part->IsDocked(); Shell::Pointer oldShell = part->GetShell(); // Reparent the part back to the main window part->Reparent(mainLayout->GetParent()); // Update container. if (oldContainer == 0) { return; } oldContainer->Remove(part); IStackableContainer::ChildrenType children = oldContainer->GetChildren(); if (wasDocked) { bool hasChildren = (children.size()> 0); if (hasChildren) { // make sure one is at least visible int childVisible = 0; for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if ((*iter)->GetControl() != 0) { childVisible++; } } // none visible, then reprarent and remove container if (oldContainer.Cast () != 0) { PartStack::Pointer folder = oldContainer.Cast(); // Is the part in the trim? bool inTrim = false; // // Safety check...there may be no FastViewManager // if (perspective.getFastViewManager() != 0) // inTrim // = perspective.getFastViewManager().getFastViews(folder.getID()).size() // > 0; if (childVisible == 0 && !inTrim) { ILayoutContainer::Pointer parentContainer = folder->GetContainer(); hasChildren = folder->GetChildren().size()> 0; // We maintain the stack as a place-holder if it has children // (which at this point would represent view place-holders) if (hasChildren) { folder->Dispose(); // replace the real container with a ContainerPlaceholder ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(folder->GetID())); placeholder->SetRealContainer(folder); parentContainer->Replace(folder, placeholder); } } else if (childVisible == 1) { LayoutTree::Pointer layout = mainLayout->GetLayoutTree(); layout = layout->Find(folder); layout->SetBounds(layout->GetBounds()); } } } if (!hasChildren) { // There are no more children in this container, so get rid of // it if (oldContainer.Cast () != 0) { //BERRY_INFO << "No children left, removing container\n"; LayoutPart::Pointer parent = oldContainer.Cast(); ILayoutContainer::Pointer parentContainer = parent->GetContainer(); if (parentContainer != 0) { parentContainer->Remove(parent); parent->Print(std::cout); parent->Dispose(); } } } } else if (!wasDocked) { if (children.empty()) { // There are no more children in this container, so get rid of // it // Turn on redraw again just in case it was off. //oldShell.setRedraw(true); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.remove(w); } else { // There are children. If none are visible hide detached // window. bool allInvisible = true; for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible) { DetachedPlaceHolder::Pointer placeholder(new DetachedPlaceHolder("", oldShell->GetBounds())); for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { oldContainer->Remove(*iter); (*iter)->SetContainer(placeholder); placeholder->Add(*iter); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.remove(w); } } } } void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); if (part.Cast () != 0) { //window.getShell().setRedraw(false); //parentWidget.setRedraw(false); PartStack::Pointer stack = part.Cast(); StackablePart::Pointer visiblePart = stack->GetSelection(); IStackableContainer::ChildrenType children = stack->GetChildren(); for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { // remove the part from its current container this->DerefPart(*iter); // add part to detached window. window->Add(*iter); } } if (visiblePart != 0) { this->BringPartToTop(visiblePart); visiblePart->SetFocus(); } //window.getShell().setRedraw(true); //parentWidget.setRedraw(true); } } void PerspectiveHelper::DetachPart(StackablePart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { IStackableContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); // remove the part from its current container this->DerefPart(part); // add part to detached window. window->Add(part); part->SetFocus(); } void PerspectiveHelper::DetachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); if (this->CanDetach() && pane != 0) { // if (getMaximizedStack() != 0) // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); Rectangle bounds = pane->GetParentBounds(); this->DetachPart(pane, bounds.x, bounds.y); } } void PerspectiveHelper::AddDetachedPart(StackablePart::Pointer part) { // Calculate detached window size. Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); bounds.x = bounds.x + (bounds.width - 300) / 2; bounds.y = bounds.y + (bounds.height - 300) / 2; this->AddDetachedPart(part, bounds); } void PerspectiveHelper::AddDetachedPart(StackablePart::Pointer part, const Rectangle& bounds) { // Detaching is disabled on some platforms .. if (!detachable) { this->AddPart(part); return; } // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); // add part to detached window. part->CreateControl(window->GetShell()->GetControl()); window->Add(part); // Open window. window->GetShell()->SetBounds(bounds.x, bounds.y, bounds.width, bounds.height); window->Open(); part->SetFocus(); } void PerspectiveHelper::DisableAllDrag() { DragUtil::RemoveDragTarget(0, dragTarget); } void PerspectiveHelper::EnableAllDrag() { DragUtil::AddDragTarget(0, dragTarget); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id) { return this->FindPart(id, ""); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId) { //BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl; // check main window. std::vector matchingParts; StackablePart::Pointer part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, mainLayout->GetChildren(), matchingParts) : this->FindPart(primaryId, mainLayout->GetChildren(), matchingParts); if (part != 0) { return part; } // check each detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { DetachedWindow::Pointer window = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, window->GetChildren(), matchingParts) : this->FindPart(primaryId, window->GetChildren(), matchingParts); if (part != 0) { return part; } } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { DetachedPlaceHolder::Pointer holder = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, holder->GetChildren(), matchingParts) : this->FindPart(primaryId, holder->GetChildren(), matchingParts); if (part != 0) { return part; } } //BERRY_INFO << "Looking through the matched parts (count: " << matchingParts.size() << ")\n"; // sort the matching parts if (matchingParts.size()> 0) { std::partial_sort(matchingParts.begin(), (matchingParts.begin()), matchingParts.end(), CompareMatchingParts()); const MatchingPart& mostSignificantPart = matchingParts.front(); return mostSignificantPart.part; } // Not found. return StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { //BERRY_INFO << "Looking for part " << id << " in a list of layout parts with size " << parts.size() << std::endl; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { StackablePart::Pointer result = this->FindPart(id, part.Cast()->GetChildren(), matchingParts); if (result != 0) return result; } else if (part.Cast() != 0) { StackablePart::Pointer result = this->FindPart(id, part.Cast()->GetChildren(), matchingParts); if (result != 0) return result; } } //BERRY_INFO << "Returning 0\n"; return StackablePart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindLayoutPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check for part equality, parts with secondary ids fail if (part->GetID() == id) { return part; } else if (part.Cast() != 0) { // Skip. } else if (part.Cast () != 0) { part = this->FindLayoutPart(id, part.Cast()->GetChildren(), matchingParts); return part; } } return LayoutPart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { //BERRY_INFO << "Looking for part " << id << " in a list of stackable parts with size " << parts.size() << std::endl; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { StackablePart::Pointer part = *iter; // check for part equality, parts with secondary ids fail if (part->GetId() == id) { if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetSecondaryId() != "") { continue; } } return part; } // check pattern matching placeholders else if (part.Cast() != 0 && part.Cast()->HasWildCard()) { Poco::RegularExpression re(id, Poco::RegularExpression::RE_CASELESS); if (re.match(part->GetId())) { matchingParts.push_back(MatchingPart(part->GetId(), "", part)); } // StringMatcher sm = new StringMatcher(part.getID(), true, false); // if (sm.match(id)) // { // matchingParts .add(new MatchingPart(part.getID(), 0, part)); // } } } //BERRY_INFO << "Returning 0\n"; return StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId, const std::list& parts, std::vector& matchingParts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check containers first if (part.Cast() != 0) { // skip } else if (part.Cast () != 0) { StackablePart::Pointer testPart = this->FindPart(primaryId, secondaryId, part.Cast()->GetChildren(), matchingParts); if (testPart != 0) { return testPart; } } } return StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId, const std::list& parts, std::vector& matchingParts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { StackablePart::Pointer part = *iter; // check for view part equality if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetId() == primaryId && ref->GetSecondaryId() == secondaryId) { return part; } } // check placeholders else if (part.Cast () != 0) { std::string id = part->GetId(); // optimization: don't bother parsing id if it has no separator -- it can't match std::string phSecondaryId = ViewFactory::ExtractSecondaryId(id); if (phSecondaryId == "") { // but still need to check for wildcard case if (id == PartPlaceholder::WILD_CARD) { matchingParts.push_back(MatchingPart(id, "", part)); } continue; } std::string phPrimaryId = ViewFactory::ExtractPrimaryId(id); // perfect matching pair if (phPrimaryId == primaryId && phSecondaryId == secondaryId) { return part; } // check for partial matching pair Poco::RegularExpression pre(phPrimaryId, Poco::RegularExpression::RE_CASELESS); if (pre.match(primaryId)) { Poco::RegularExpression sre(phSecondaryId, Poco::RegularExpression::RE_CASELESS); if (sre.match(secondaryId)) { matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part)); } } } } return StackablePart::Pointer(0); } bool PerspectiveHelper::HasPlaceholder(const std::string& id) { return this->HasPlaceholder(id, 0); } bool PerspectiveHelper::HasPlaceholder(const std::string& primaryId, const std::string& secondaryId) { StackablePart::Pointer testPart; if (secondaryId == "") { testPart = this->FindPart(primaryId); } else { testPart = this->FindPart(primaryId, secondaryId); } return (testPart != 0 && testPart.Cast () != 0); } PartSashContainer::Pointer PerspectiveHelper::GetLayout() const { return mainLayout; } bool PerspectiveHelper::IsActive() { return active; } float PerspectiveHelper::GetDockingRatio(StackablePart::Pointer source, LayoutPart::Pointer target) { if ((source.Cast () != 0 || source.Cast () != 0) && target.Cast () != 0) { return 0.25f; } return 0.5f; } void PerspectiveHelper::RemovePart(StackablePart::Pointer part) { // Reparent the part back to the main window void* parent = mainLayout->GetParent(); part->Reparent(parent); // Replace part with a placeholder IStackableContainer::Pointer container = part->GetContainer(); if (container != 0) { std::string placeHolderId = part->GetPlaceHolderId(); container->Replace(part, StackablePart::Pointer(new PartPlaceholder(placeHolderId))); // // If the parent is root we're done. Do not try to replace // // it with placeholder. // if (container == mainLayout) // { // return; // } // If the parent is empty replace it with a placeholder. std::list children = container->GetChildren(); bool allInvisible = true; for (std::list::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible && (container.Cast () != 0)) { // what type of window are we in? LayoutPart::Pointer cPart = container.Cast(); //Window oldWindow = cPart.getWindow(); bool wasDocked = cPart->IsDocked(); Shell::Pointer oldShell = cPart->GetShell(); if (wasDocked) { // PR 1GDFVBY: ViewStack not disposed when page // closed. if (container.Cast () != 0) { container.Cast()->Dispose(); } // replace the real container with a // ContainerPlaceholder ILayoutContainer::Pointer parentContainer = cPart->GetContainer(); ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(cPart->GetID())); placeholder->SetRealContainer(container); parentContainer->Replace(cPart, placeholder); } else { DetachedPlaceHolder::Pointer placeholder( new DetachedPlaceHolder("", oldShell->GetBounds())); //$NON-NLS-1$ for (std::list::iterator childIter2 = children.begin(); childIter2 != children.end(); ++childIter2) { (*childIter2)->GetContainer()->Remove(*childIter2); (*childIter2)->SetContainer(placeholder); placeholder->Add(*childIter2); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.remove(w); } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(StackablePart::Pointer part) { // Look for a PartPlaceholder that will tell us how to position this // object std::vector placeholders = this->CollectPlaceholders(); for (unsigned int i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetCompoundId() == part->GetCompoundId()) { // found a matching placeholder which we can replace with the // new View IStackableContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { if (container.Cast () != 0) { // One of the children is now visible so replace the // ContainerPlaceholder with the real container ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(IStackableContainer::Pointer(0)); } container->Replace(placeholders[i], part); return; } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part) { // Look for a ContainerPlaceholder that will tell us how to position this // object std::vector placeholders(this->CollectContainerPlaceholders()); for (std::size_t i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetID() == part->GetID()) { // found a matching placeholder which we can replace with the // new container ILayoutContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { // if (container.Cast () != 0) // { // // One of the children is now visible so replace the // // ContainerPlaceholder with the real container // ContainerPlaceholder::Pointer containerPlaceholder = // container.Cast(); // ILayoutContainer::Pointer parentContainer = // containerPlaceholder->GetContainer(); // container // = containerPlaceholder->GetRealContainer(); // if (container.Cast () != 0) // { // parentContainer->Replace(containerPlaceholder, // container.Cast()); // } // containerPlaceholder->SetRealContainer(IStackableContainer::Pointer(0)); // } container->Replace(placeholders[i], part); return; } } } } bool PerspectiveHelper::RestoreState(IMemento::Pointer memento) { // Restore main window. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->RestoreState(childMem); bool r = mainLayout->RestoreState(childMem); // Restore each floating window. if (detachable) { std::vector detachedWindows(memento->GetChildren( WorkbenchConstants::TAG_DETACHED_WINDOW)); for (std::vector::iterator iter = detachedWindows.begin(); iter != detachedWindows.end(); ++iter) { DetachedWindow::Pointer win(new DetachedWindow(page)); detachedWindowList.push_back(win); win->RestoreState(*iter); } std::vector childrenMem(memento->GetChildren( WorkbenchConstants::TAG_HIDDEN_WINDOW)); for (std::vector::iterator iter = childrenMem.begin(); iter != childrenMem.end(); ++iter) { DetachedPlaceHolder::Pointer holder( new DetachedPlaceHolder("", Rectangle(0, 0, 0, 0))); holder->RestoreState(*iter); detachedPlaceHolderList.push_back(holder); } } // Get the cached id of the currently maximized stack //maximizedStackId = childMem.getString(IWorkbenchConstants.TAG_MAXIMIZED); return r; } bool PerspectiveHelper::SaveState(IMemento::Pointer memento) { // Persist main window. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->SaveState(childMem); bool r = mainLayout->SaveState(childMem); if (detachable) { // Persist each detached window. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_DETACHED_WINDOW); (*iter)->SaveState(childMem); } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_HIDDEN_WINDOW); (*iter)->SaveState(childMem); } } // Write out the id of the maximized (View) stack (if any) // NOTE: we only write this out if it's a ViewStack since the // Editor Area is handled by the perspective // if (maximizedStack.Cast () != 0) // { // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, // maximizedStack.getID()); // } // else if (maximizedStackId != 0) // { // // Maintain the cache if the perspective has never been activated // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, maximizedStackId); // } return r; } void PerspectiveHelper::UpdateBoundsMap() { boundsMap.clear(); // Walk the layout gathering the current bounds of each stack // and the editor area std::list kids = mainLayout->GetChildren(); for (std::list::iterator iter = kids.begin(); iter != kids.end(); ++iter) { if (iter->Cast () != 0) { PartStack::Pointer vs = iter->Cast(); boundsMap.insert(std::make_pair(vs->GetID(), vs->GetBounds())); } else if (iter->Cast () != 0) { EditorSashContainer::Pointer esc = iter->Cast(); boundsMap.insert(std::make_pair(esc->GetID(), esc->GetBounds())); } } } void PerspectiveHelper::ResetBoundsMap() { boundsMap.clear(); } Rectangle PerspectiveHelper::GetCachedBoundsFor(const std::string& id) { return boundsMap[id]; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp index 4803a6265c..02433d51e6 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp @@ -1,172 +1,172 @@ /*========================================================================= 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 "berryStackablePart.h" #include "berryIStackableContainer.h" #include "berryDetachedWindow.h" #include "../berryIWorkbenchWindow.h" #include "../tweaklets/berryGuiWidgetsTweaklet.h" #include "../berryImageDescriptor.h" namespace berry { StackablePart::StackablePart(std::string id_) : id(id_) { } IStackableContainer::Pointer StackablePart::GetContainer() const { return container; } void StackablePart::SetContainer(IStackableContainer::Pointer container) { this->container = container; } void StackablePart::Reparent(void* newParent) { void* control = this->GetControl(); - GuiWidgetsTweaklet::Pointer guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); + GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void StackablePart::DescribeLayout(std::string& /*description*/) const { } std::string StackablePart::GetPlaceHolderId() const { return this->GetId(); } std::string StackablePart::GetId() const { return id; } void StackablePart::SetId(const std::string& id) { this->id = id; } void StackablePart::SetFocus() { } void StackablePart::SetBounds(const Rectangle& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } Rectangle StackablePart::GetBounds() { return Rectangle(); } Point StackablePart::GetSize() { Rectangle r = this->GetBounds(); Point ptSize(r.width, r.height); return ptSize; } bool StackablePart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer StackablePart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer StackablePart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } std::string StackablePart::GetCompoundId() { return this->GetId(); } bool StackablePart::IsPlaceHolder() const { return false; } void StackablePart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp index 44b6d8851f..8cdd2bc95e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.cpp @@ -1,26 +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 { -std::map Tweaklets::defaults; -std::map Tweaklets::tweaklets; +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"; + 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/berryTweaklets.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.h index f9d37afeb5..1807b7769a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTweaklets.h @@ -1,188 +1,157 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYTWEAKLETS_H_ #define BERRYTWEAKLETS_H_ -#include -#include -#include +#include -#include -#include -#include -#include +#include -#include +namespace berry { -namespace berry +struct BERRY_UI TweakKey_base { + QString tweakClass; -class BERRY_UI Tweaklets -{ + /** + * @param tweakClass + */ + TweakKey_base(const QString& _tweakClass); -public: + bool operator==(const TweakKey_base& obj) const; + bool operator<(const TweakKey_base& obj) const; +}; - struct TweakKey_base - { - std::string tweakClass; +} - /** - * @param tweakClass - */ - TweakKey_base(const std::string& _tweakClass) : - tweakClass(_tweakClass) - { +BERRY_UI uint qHash(const berry::TweakKey_base& key); - } +#include +#include +#include - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - // int hashCode() { - // final int prime = 31; - // int result = 1; - // result = prime * result - // + ((tweakClass == null) ? 0 : tweakClass.hashCode()); - // return result; - // } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - bool operator==(const TweakKey_base& obj) const - { - if (this == &obj) - return true; - return tweakClass == obj.tweakClass; - } +namespace berry { - bool operator<(const TweakKey_base& obj) const - { - return tweakClass < obj.tweakClass; - } - }; +class BERRY_UI Tweaklets +{ + +public: template struct TweakKey: public TweakKey_base { TweakKey() : TweakKey_base("") { - tweakClass = I::GetManifestName(); + + tweakClass = QString(qobject_interface_iid()); } - TweakKey(const std::string& _tweakClass) : + TweakKey(const QString& _tweakClass) : TweakKey_base(_tweakClass) { } }; static void SetDefault(const TweakKey_base& definition, - Object::Pointer implementation) - { - defaults.insert(std::make_pair(definition, implementation)); - } + QObject* implementation); - static void Clear() - { - std::cout << "Clearing tweaklets\n"; - tweaklets.clear(); - defaults.clear(); - } + static void Clear(); template - static typename I::Pointer Get(const TweakKey& definition) + static I* Get(const TweakKey& definition) { TweakletMap::const_iterator iter = tweaklets.find(definition); - typename I::Pointer result; + QObject* result; if (iter == tweaklets.end()) { result = CreateTweaklet(definition); - if (result.IsNull()) + if (result == 0) { result = GetDefault(definition); } - poco_assert(result.IsNotNull()); - tweaklets.insert(std::make_pair(definition, result)); - return result; + Q_ASSERT(result != 0); + tweaklets.insert(definition, result); + return qobject_cast(result); } - return iter->second.Cast(); + return qobject_cast(iter.value()); } private: - typedef std::map TweakletMap; + typedef QHash TweakletMap; static TweakletMap defaults; static TweakletMap tweaklets; /** * @param definition * @return */ template - static typename I::Pointer GetDefault(const TweakKey& definition) + static QObject* GetDefault(const TweakKey& definition) { TweakletMap::const_iterator iter = defaults.find(definition); if (iter == defaults.end()) - return typename I::Pointer(0); + return 0; - return iter->second.Cast(); + return iter.value(); } /** * @param definition * @return */ template - static typename I::Pointer CreateTweaklet(const TweakKey& definition) + static QObject* CreateTweaklet(const TweakKey& definition) { - std::vector elements = Platform - ::GetExtensionPointService() - ->GetConfigurationElementsFor("org.blueberry.ui.tweaklets"); //$NON-NLS-1$ + std::vector elements = + Platform::GetExtensionPointService() + ->GetConfigurationElementsFor("org.blueberry.ui.tweaklets"); //$NON-NLS-1$ for (unsigned int i = 0; i < elements.size(); i++) { std::string attr; if (elements[i]->GetAttribute("definition", attr) && - definition.tweakClass == attr) + definition.tweakClass == QString::fromStdString(attr)) { try { - typename I::Pointer tweaklet(elements[i]->CreateExecutableExtension("implementation")); //$NON-NLS-1$ - tweaklets.insert(std::make_pair(definition, tweaklet)); + QObject* tweaklet = elements[i]->CreateExecutableExtension("implementation"); + tweaklets.insert(definition, tweaklet); return tweaklet; } catch (CoreException e) { //StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERR, BERRY_ERROR << "Error with extension " << elements[i] << e.what(); // StatusManager.LOG); } } } - return typename I::Pointer(0); + return 0; } }; } + #endif /* BERRYTWEAKLETS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp index 6e87ad8cd7..c870944b5c 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 "../tweaklets/berryWorkbenchTweaklet.h" - #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; 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; 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/berryWorkbenchPage.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp index 86d65407a0..aad8d7ac4b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp @@ -1,4111 +1,4112 @@ /*========================================================================= 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/berryGuiWidgetsTweaklet.h" +#include "../tweaklets/berryWorkbenchPageTweaklet.h" + #include "berryWorkbenchPage.h" #include "berryPartSite.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPerspective.h" #include "berryLayoutPartSash.h" #include "berryWorkbenchPlugin.h" #include "berryEditorAreaHelper.h" #include "berrySaveablesList.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTreeNode.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartService.h" #include "berryStickyViewManager.h" #include "intro/berryIntroConstants.h" #include "intro/berryViewIntroAdapterPart.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" #include "../dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" #include "../berryUIException.h" #include "../berryPlatformUI.h" #include "berryPartPane.h" #include "../berryImageDescriptor.h" #include #include namespace berry { WorkbenchPage::ActivationOrderPred::ActivationOrderPred( WorkbenchPage::ActivationList* al) : activationList(al) { } bool WorkbenchPage::ActivationOrderPred::operator()( const IViewReference::Pointer o1, const IViewReference::Pointer o2) const { WorkbenchPage::ActivationList::PartListIter pos1 = activationList->IndexOf( o1.Cast ()); WorkbenchPage::ActivationList::PartListIter pos2 = activationList->IndexOf( o2.Cast ()); return pos1 < pos2; } void WorkbenchPage::PerspectiveList::UpdateActionSets( Perspective::Pointer /*oldPersp*/, Perspective::Pointer /*newPersp*/) { //TODO WorkbenchPage action sets // // Update action sets // // IContextService service = (IContextService) window // .getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // if (newPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = newPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.showAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = newPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.maskAction(descriptor); // } // } // // if (oldPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = oldPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.hideAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = oldPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.unmaskAction(descriptor); // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } } WorkbenchPage::PerspectiveList::PerspectiveList() { } void WorkbenchPage::PerspectiveList::Reorder( IPerspectiveDescriptor::Pointer perspective, int newLoc) { PerspectiveListType::iterator oldLocation = openedList.end(); Perspective::Pointer movedPerspective; for (PerspectiveListType::iterator iterator = openedList.begin(); iterator != openedList.end(); ++iterator) { Perspective::Pointer openPerspective = *iterator; if (openPerspective->GetDesc() == perspective) { oldLocation = std::find(openedList.begin(), openedList.end(), openPerspective); movedPerspective = openPerspective; } } PerspectiveListType::iterator newLocation = openedList.begin(); for (int i = 0; i < newLoc; ++i, ++newLocation) ; if (oldLocation == newLocation) { return; } openedList.erase(oldLocation); openedList.insert(newLocation, movedPerspective); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetSortedPerspectives() { return usedList; } bool WorkbenchPage::PerspectiveList::Add(Perspective::Pointer perspective) { openedList.push_back(perspective); usedList.push_front(perspective); //It will be moved to top only when activated. return true; } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::Begin() { return openedList.begin(); } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::End() { return openedList.end(); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetOpenedPerspectives() { return openedList; } bool WorkbenchPage::PerspectiveList::Remove(Perspective::Pointer perspective) { if (active == perspective) { this->UpdateActionSets(active, Perspective::Pointer(0)); active = 0; } usedList.remove(perspective); PerspectiveListType::size_type origSize = openedList.size(); openedList.remove(perspective); return openedList.size() != origSize; } void WorkbenchPage::PerspectiveList::Swap(Perspective::Pointer oldPerspective, Perspective::Pointer newPerspective) { PerspectiveListType::iterator oldIter = std::find(openedList.begin(), openedList.end(), oldPerspective); PerspectiveListType::iterator newIter = std::find(openedList.begin(), openedList.end(), newPerspective); if (oldIter == openedList.end() || newIter == openedList.end()) { return; } std::iter_swap(oldIter, newIter); } bool WorkbenchPage::PerspectiveList::IsEmpty() { return openedList.empty(); } Perspective::Pointer WorkbenchPage::PerspectiveList::GetActive() { return active; } Perspective::Pointer WorkbenchPage::PerspectiveList::GetNextActive() { if (active == 0) { if (usedList.empty()) { return Perspective::Pointer(0); } else { return usedList.back(); } } else { if (usedList.size() < 2) { return Perspective::Pointer(0); } else { return *(++usedList.rbegin()); } } } WorkbenchPage::PerspectiveList::PerspectiveListType::size_type WorkbenchPage::PerspectiveList::Size() { return openedList.size(); } void WorkbenchPage::PerspectiveList::SetActive(Perspective::Pointer perspective) { if (perspective == active) { return; } this->UpdateActionSets(active, perspective); active = perspective; if (perspective != 0) { usedList.remove(perspective); usedList.push_back(perspective); } } WorkbenchPage::ActivationList::ActivationList(WorkbenchPage* page) : page(page) { } void WorkbenchPage::ActivationList::SetActive(SmartPointer part) { if (parts.empty()) { return; } IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref) { if (ref == parts.back()) { return; } parts.erase(std::find(parts.begin(), parts.end(), ref)); parts.push_back(ref); } } void WorkbenchPage::ActivationList::BringToTop(SmartPointer< IWorkbenchPartReference> ref) { IStackableContainer::Pointer targetContainer(page->GetContainer(ref)); PartListIter newIndex = this->LastIndexOfContainer(targetContainer); if (newIndex != parts.end() && ref == *newIndex) { return; } if (newIndex == parts.end()) { parts.push_back(ref); } else { PartListType::size_type index = newIndex - parts.begin(); parts.erase(std::find(parts.begin(), parts.end(), ref)); PartListIter insertIndex = parts.begin() + index; parts.insert(insertIndex, ref); } } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::LastIndexOfContainer( SmartPointer container) { PartListReverseIter i = parts.rbegin(); while (i != parts.rend()) { IWorkbenchPartReference::Pointer ref(*i); IStackableContainer::Pointer cnt(page->GetContainer(ref)); if (cnt == container) { return --i.base(); } ++i; } return parts.end(); } void WorkbenchPage::ActivationList::SetActive(SmartPointer< IWorkbenchPartReference> ref) { this->SetActive(ref->GetPart(true)); } void WorkbenchPage::ActivationList::Add( SmartPointer ref) { if (std::find(parts.begin(), parts.end(), ref) != parts.end()) { return; } ref->GetPart(false); parts.push_front(ref); } SmartPointer WorkbenchPage::ActivationList::GetActive() { if (parts.empty()) { return IWorkbenchPart::Pointer(0); } return this->GetActive(parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetPreviouslyActive() { if (parts.size() < 2) { return IWorkbenchPart::Pointer(0); } return this->GetActive(--parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( bool editorsOnly) { return this->GetActiveReference(parts.end(), editorsOnly); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer part) { IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref == 0) { return parts.end(); } return std::find(parts.begin(), parts.end(), ref); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer ref) { return std::find(parts.begin(), parts.end(), ref); } bool WorkbenchPage::ActivationList::Remove( SmartPointer ref) { bool contains = std::find(parts.begin(), parts.end(), ref) != parts.end(); parts.erase(std::find(parts.begin(), parts.end(), ref)); return contains; } SmartPointer WorkbenchPage::ActivationList::GetTopEditor() { IEditorReference::Pointer editor = this->GetActiveReference(parts.end(), true).Cast (); if (editor == 0) { return IEditorPart::Pointer(0); } return editor->GetEditor(true); } SmartPointer WorkbenchPage::ActivationList::GetActive( PartListIter start) { IWorkbenchPartReference::Pointer ref(this->GetActiveReference(start, false)); if (!ref) { return IWorkbenchPart::Pointer(0); } return ref->GetPart(true); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly) { // First look for parts that aren't obscured by the current zoom state IWorkbenchPartReference::Pointer nonObscured = this->GetActiveReference( start, editorsOnly, true); if (nonObscured) { return nonObscured; } // Now try all the rest of the parts return this->GetActiveReference(start, editorsOnly, false); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly, bool /*skipPartsObscuredByZoom*/) { std::vector views = page->GetViewReferences(); PartListReverseIter i(start); while (i != parts.rend()) { WorkbenchPartReference::Pointer ref(i->Cast ()); if (editorsOnly && (ref.Cast () == 0)) { ++i; continue; } // Skip parts whose containers have disabled auto-focus PartPane::Pointer pane(ref->GetPane()); if (pane) { if (!pane->AllowsAutoFocus()) { ++i; continue; } // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } } // Skip fastviews (unless overridden) if (IViewReference::Pointer viewRef = ref.Cast()) { //if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { for (unsigned int j = 0; j < views.size(); j++) { if (views[j] == viewRef) { return viewRef.Cast (); } } //} } else { return ref.Cast (); } ++i; } return IWorkbenchPartReference::Pointer(0); } std::vector > WorkbenchPage::ActivationList::GetEditors() { std::vector editors; for (PartListIter i = parts.begin(); i != parts.end(); ++i) { if (IEditorReference::Pointer part = i->Cast()) { editors.push_back(part); } } return editors; } std::vector > WorkbenchPage::ActivationList::GetParts() { std::vector views(page->GetViewReferences()); std::vector resultList; for (PartListIter iterator = parts.begin(); iterator != parts.end(); ++iterator) { if (IViewReference::Pointer ref = iterator->Cast()) { //Filter views from other perspectives for (unsigned int i = 0; i < views.size(); i++) { if (ref == views[i]) { resultList.push_back(ref); break; } } } else { resultList.push_back(*iterator); } } return resultList; } void WorkbenchPage::ActionSwitcher::UpdateActivePart( IWorkbenchPart::Pointer newPart) { IWorkbenchPart::Pointer _activePart = this->activePart.Lock(); IEditorPart::Pointer _topEditor = this->topEditor.Lock(); if (_activePart == newPart) { return; } bool isNewPartAnEditor = newPart.Cast ().IsNotNull(); if (isNewPartAnEditor) { std::string oldId; if (_topEditor) { oldId = _topEditor->GetSite()->GetId(); } std::string newId = newPart->GetSite()->GetId(); // if the active part is an editor and the new editor // is the same kind of editor, then we don't have to do // anything if (activePart == topEditor && newId == oldId) { activePart = newPart; topEditor = newPart.Cast (); return; } // remove the contributions of the old editor // if it is a different kind of editor if (oldId != newId) { this->DeactivateContributions(_topEditor, true); } // if a view was the active part, disable its contributions if (_activePart && _activePart != _topEditor) { this->DeactivateContributions(_activePart, true); } // show (and enable) the contributions of the new editor // if it is a different kind of editor or if the // old active part was a view if (newId != oldId || _activePart != _topEditor) { this->ActivateContributions(newPart, true); } } else if (newPart.IsNull()) { if (_activePart) { // remove all contributions this->DeactivateContributions(_activePart, true); } } else { // new part is a view // if old active part is a view, remove all contributions, // but if old part is an editor only disable if (_activePart) { this->DeactivateContributions(_activePart, _activePart.Cast ().IsNotNull()); } this->ActivateContributions(newPart, true); } //TODO WorkbenchPage action sets // ArrayList newActionSets = 0; // if (isNewPartAnEditor || (activePart == topEditor && newPart == 0)) // { // newActionSets = calculateActionSets(newPart, 0); // } // else // { // newActionSets = calculateActionSets(newPart, topEditor); // } // // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } if (isNewPartAnEditor) { topEditor = newPart.Cast (); } else if (activePart == topEditor && newPart.IsNull()) { // since we removed all the contributions, we clear the top // editor topEditor.Reset(); } activePart = newPart; } void WorkbenchPage::ActionSwitcher::UpdateTopEditor( IEditorPart::Pointer newEditor) { if (topEditor.Lock() == newEditor) { return; } if (activePart == topEditor) { this->UpdateActivePart(newEditor); return; } std::string oldId; if (!topEditor.Expired()) { oldId = topEditor.Lock()->GetSite()->GetId(); } std::string newId; if (newEditor.IsNotNull()) { newId = newEditor->GetSite()->GetId(); } if (oldId == newId) { // we don't have to change anything topEditor = newEditor; return; } // Remove the contributions of the old editor if (!topEditor.Expired()) { this->DeactivateContributions(topEditor.Lock(), true); } // Show (disabled) the contributions of the new editor if (newEditor.IsNotNull()) { this->ActivateContributions(newEditor, false); } // ArrayList newActionSets = calculateActionSets(activePart, newEditor); // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } topEditor = newEditor; } void WorkbenchPage::ActionSwitcher::ActivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*enable*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->ActivateActionBars(enable); } void WorkbenchPage::ActionSwitcher::DeactivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*remove*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->DeactivateActionBars(remove); } const IExtensionPoint* WorkbenchPage::GetPerspectiveExtensionPoint() { return Platform::GetExtensionPointService()->GetExtensionPoint( PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const std::string& layoutID, IAdaptable* input) { if (layoutID == "") { throw WorkbenchException("Perspective ID is undefined"); } this->Register(); this->Init(w, layoutID, input, true); this->UnRegister(false); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, IAdaptable* input) { this->Register(); this->Init(w, "", input, false); this->UnRegister(false); } void WorkbenchPage::Activate(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } if (window->IsClosing()) { return; } // if (composite!=0 && composite.isVisible() && !((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // Activate part. //if (window.getActivePage() == this) { IWorkbenchPartReference::Pointer ref = this->GetReference(part); this->InternalBringToTop(ref); this->SetActivePart(part); } void WorkbenchPage::ActivatePart(const IWorkbenchPart::Pointer part) { // Platform.run(new SafeRunnable(WorkbenchMessages.WorkbenchPage_ErrorActivatingView) // { // public void WorkbenchPage::run() // { if (part.IsNotNull()) { //part.setFocus(); PartPane::Pointer pane = this->GetPane(part); pane->SetFocus(); PartSite::Pointer site = part->GetSite().Cast (); pane->ShowFocus(true); //this->UpdateTabList(part); //SubActionBars bars = (SubActionBars) site.getActionBars(); //bars.partChanged(part); } // } // } // ); } void WorkbenchPage::AddPartListener(IPartListener::Pointer l) { partList->GetPartService()->AddPartListener(l); } void WorkbenchPage::AddSelectionListener(ISelectionListener::Pointer listener) { selectionService->AddSelectionListener(listener); } void WorkbenchPage::AddSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->AddSelectionListener(partId, listener); } void WorkbenchPage::AddPostSelectionListener( ISelectionListener::Pointer listener) { selectionService->AddPostSelectionListener(listener); } void WorkbenchPage::AddPostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->AddPostSelectionListener(partId, listener); } IStackableContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return IStackableContainer::Pointer(0); } return pane->GetContainer(); } IStackableContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPartReference::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return IStackableContainer::Pointer(0); } return pane->GetContainer(); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPart::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return this->GetPane(this->GetReference(part)); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPartReference::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return part.Cast ()->GetPane(); } bool WorkbenchPage::InternalBringToTop(IWorkbenchPartReference::Pointer part) { bool broughtToTop = false; // Move part. if (part.Cast ().IsNotNull()) { IStackableContainer::Pointer container = this->GetContainer(part); if (container.Cast () != 0) { PartStack::Pointer stack = container.Cast (); PartPane::Pointer newPart = this->GetPane(part); if (stack->GetSelection() != newPart) { stack->SetSelection(newPart); } broughtToTop = true; } } else if (part.Cast ().IsNotNull()) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { broughtToTop = persp->BringToTop(part.Cast ()); } } // Ensure that this part is considered the most recently activated part // in this stack activationList->BringToTop(part); return broughtToTop; } void WorkbenchPage::BringToTop(IWorkbenchPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return; } // if (!((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // std::string label; // debugging only // if (UIStats.isDebugging(UIStats.BRING_PART_TO_TOP)) // { // label = part != 0 ? part.getTitle() : "none"; //$NON-NLS-1$ // } IWorkbenchPartReference::Pointer ref = this->GetReference(part); IStackableContainer::Pointer activeEditorContainer = this->GetContainer( this->GetActiveEditor().Cast ()); IStackableContainer::Pointer activePartContainer = this->GetContainer( this->GetActivePart()); IStackableContainer::Pointer newPartContainer = this->GetContainer(part); if (newPartContainer == activePartContainer) { this->MakeActive(ref); } else if (newPartContainer == activeEditorContainer) { if (ref.Cast () != 0) { if (part != 0) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () != 0) { ref = site.Cast ()->GetPane()->GetPartReference(); } } this->MakeActiveEditor(ref.Cast ()); } else { this->MakeActiveEditor(IEditorReference::Pointer(0)); } } else { this->InternalBringToTop(ref); if (ref != 0) { partList->FirePartBroughtToTop(ref); } } } void WorkbenchPage::BusyResetPerspective() { ViewIntroAdapterPart::Pointer introViewAdapter = dynamic_cast (GetWorkbenchWindow() ->GetWorkbench()->GetIntroManager())->GetIntroAdapterPart().Cast< ViewIntroAdapterPart> (); // PartPane introPane = 0; // boolean introFullScreen = false; // if (introViewAdapter != 0) // { // introPane = ((PartSite) introViewAdapter.getSite()).getPane(); // introViewAdapter.setHandleZoomEvents(false); // introFullScreen = introPane.isZoomed(); // } // //try to prevent intro flicker. // if (introFullScreen) // { // window.getShell().setRedraw(false); // } // try // { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } // Get the current perspective. // This describes the working layout of the page and differs from // the original template. Perspective::Pointer oldPersp = this->GetActivePerspective(); // Map the current perspective to the original template. // If the original template cannot be found then it has been deleted. // In that case just return. (PR#1GDSABU). IPerspectiveRegistry* reg = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry(); PerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId( oldPersp->GetDesc()->GetId()).Cast (); if (desc == 0) { desc = reg->FindPerspectiveWithId(oldPersp ->GetDesc().Cast< PerspectiveDescriptor> ()->GetOriginalId()).Cast< PerspectiveDescriptor> (); } if (desc == 0) { return; } // Notify listeners that we are doing a reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET); // Create new persp from original template. // Suppress the perspectiveOpened and perspectiveClosed events otherwise it looks like two // instances of the same perspective are open temporarily (see bug 127470). Perspective::Pointer newPersp = this->CreatePerspective(desc, false); if (newPersp == 0) { // We're not going through with the reset, so it is complete. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); return; } // Update the perspective list and shortcut perspList.Swap(oldPersp, newPersp); // Install new persp. this->SetPerspective(newPersp); // Destroy old persp. this->DisposePerspective(oldPersp, false); // Update the Coolbar layout. this->ResetToolBarLayout(); // restore the maximized intro if (introViewAdapter) { try { // ensure that the intro is visible in the new perspective ShowView(IntroConstants::INTRO_VIEW_ID); // if (introFullScreen) // { // toggleZoom(introPane.getPartReference()); // } } catch (PartInitException& e) { //TODO IStatus WorkbenchPlugin::Log("Could not restore intro", e); // WorkbenchPlugin.getStatus(e)); } // finally // { // // we want the intro back to a normal state before we fire the event // introViewAdapter.setHandleZoomEvents(true); // } } // Notify listeners that we have completed our reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); // } // finally // { // // reset the handling of zoom events (possibly for the second time) in case there was // // an exception thrown // if (introViewAdapter != 0) // { // introViewAdapter.setHandleZoomEvents(true); // } // // if (introFullScreen) // { // window.getShell().setRedraw(true); // } // } } void WorkbenchPage::BusySetPerspective(IPerspectiveDescriptor::Pointer desc) { // Create new layout. std::string label = desc->GetId(); // debugging only Perspective::Pointer newPersp; //try //{ //UIStats.start(UIStats.SWITCH_PERSPECTIVE, label); PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(realDesc); if (newPersp == 0) { newPersp = this->CreatePerspective(realDesc, true); if (newPersp == 0) { return; } } // Change layout. this->SetPerspective(newPersp); // } // catch (std::exception& e) // { // UIStats.end(UIStats.SWITCH_PERSPECTIVE, desc.getId(), label); // throw e; // } } IViewPart::Pointer WorkbenchPage::BusyShowView(const std::string& viewID, const std::string& secondaryID, int mode) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewPart::Pointer(0); } // If this view is already visible just return. IViewReference::Pointer ref = persp->FindView(viewID, secondaryID); IViewPart::Pointer view; if (ref != 0) { view = ref->GetView(true); } if (view != 0) { this->BusyShowView(view, mode); return view; } // Show the view. view = persp->ShowView(viewID, secondaryID); if (view != 0) { this->BusyShowView(view, mode); IWorkbenchPartReference::Pointer partReference = this->GetReference(view); PartPane::Pointer partPane = this->GetPane(partReference); partPane->SetInLayout(true); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, GetPerspective(), partReference, CHANGE_VIEW_SHOW); window->FirePerspectiveChanged(thisPage, GetPerspective(), CHANGE_VIEW_SHOW); } return view; } void WorkbenchPage::BusyShowView(IViewPart::Pointer part, int mode) { // if (!((GrabFocus) Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } if (mode == VIEW_ACTIVATE) { this->Activate(part); } else if (mode == VIEW_VISIBLE) { IWorkbenchPartReference::Pointer ref = this->GetActivePartReference(); // if there is no active part or it's not a view, bring to top if (ref == 0 || ref.Cast () == 0) { this->BringToTop(part); } else { // otherwise check to see if the we're in the same stack as the active view IViewReference::Pointer activeView = ref.Cast (); std::vector viewStack = this->GetViewReferenceStack(part); for (unsigned int i = 0; i < viewStack.size(); i++) { if (viewStack[i] == activeView) { return; } } this->BringToTop(part); } } } bool WorkbenchPage::CertifyPart(IWorkbenchPart::Pointer part) { //Workaround for bug 22325 if (part != 0 && part->GetSite().Cast () == 0) { return false; } if (part.Cast () != 0) { IEditorReference::Pointer ref = this->GetReference(part).Cast< IEditorReference> (); return ref != 0 && this->GetEditorManager()->ContainsEditor(ref); } if (part.Cast () != 0) { Perspective::Pointer persp = this->GetActivePerspective(); return persp != 0 && persp->ContainsView(part.Cast ()); } return false; } bool WorkbenchPage::Close() { bool ret; //BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { ret = window->ClosePage(IWorkbenchPage::Pointer(this), true); // } // }); return ret; } bool WorkbenchPage::CloseAllSavedEditors() { // get the Saved editors std::list editors = this->GetEditorReferences(); std::list savedEditors; for (std::list::iterator iter = editors.begin(); iter != editors.end(); ++iter) { IEditorReference::Pointer editor = *iter; if (!editor->IsDirty()) { savedEditors.push_back(editor); } } //there are no unsaved editors if (savedEditors.empty()) { return true; } return this->CloseEditors(savedEditors, false); } bool WorkbenchPage::CloseAllEditors(bool save) { return this->CloseEditors(this->GetEditorReferences(), save); } void WorkbenchPage::UpdateActivePart() { if (this->IsDeferred()) { return; } IWorkbenchPartReference::Pointer oldActivePart = partList->GetActivePartReference(); IWorkbenchPartReference::Pointer oldActiveEditor = partList->GetActiveEditorReference(); IWorkbenchPartReference::Pointer newActivePart; IEditorReference::Pointer newActiveEditor; if (!window->IsClosing()) { // If an editor is active, try to keep an editor active if (oldActiveEditor && oldActivePart == oldActiveEditor) { newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); newActivePart = newActiveEditor; if (newActivePart == 0) { // Only activate a non-editor if there's no editors left newActivePart = activationList->GetActiveReference(false); } } else { // If a non-editor is active, activate whatever was activated most recently newActivePart = activationList->GetActiveReference(false); if (newActivePart.Cast () != 0) { // If that happens to be an editor, make it the active editor as well newActiveEditor = newActivePart.Cast (); } else { // Otherwise, select whatever editor was most recently active newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); } } } if (oldActiveEditor != newActiveEditor) { this->MakeActiveEditor(newActiveEditor); } if (newActivePart != oldActivePart) { this->MakeActive(newActivePart); } } void WorkbenchPage::MakeActive(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { IWorkbenchPart::Pointer newActive = ref->GetPart(true); if (newActive == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { this->Activate(newActive); } } } void WorkbenchPage::MakeActiveEditor(IEditorReference::Pointer ref) { if (ref == this->GetActiveEditorReference()) { return; } IEditorPart::Pointer part = (ref == 0) ? IEditorPart::Pointer(0) : ref->GetEditor(true); if (part) { editorMgr->SetVisibleEditor(ref, false); //navigationHistory.MarkEditor(part); } actionSwitcher.UpdateTopEditor(part); if (ref) { activationList->BringToTop(this->GetReference(part)); } partList->SetActiveEditor(ref); } bool WorkbenchPage::CloseEditors( const std::list& refArray, bool save) { if (refArray.empty()) { return true; } IWorkbenchPage::Pointer thisPage(this); // Check if we're being asked to close any parts that are already closed or cannot // be closed at this time std::vector editorRefs; for (std::list::const_iterator iter = refArray.begin(); iter != refArray.end(); ++iter) { IEditorReference::Pointer reference = *iter; // If we're in the middle of creating this part, this is a programming error. Abort the entire // close operation. This usually occurs if someone tries to open a dialog in a method that // isn't allowed to do so, and a *syncExec tries to close the part. If this shows up in a log // file with a dialog's event loop on the stack, then the code that opened the dialog is usually // at fault. if (partBeingActivated == reference) { Poco::RuntimeException re( "WARNING: Blocked recursive attempt to close part " //$NON-NLS-1$ + partBeingActivated->GetId() + " while still in the middle of activating it"); WorkbenchPlugin::Log(re); return false; } // if (reference.Cast () != 0) // { // WorkbenchPartReference::Pointer ref = reference.Cast(); // // // If we're being asked to close a part that is disposed (ie: already closed), // // skip it and proceed with closing the remaining parts. // if (ref.isDisposed()) // { // continue; // } // } editorRefs.push_back(reference); } // notify the model manager before the close std::list partsToClose; for (unsigned int i = 0; i < editorRefs.size(); i++) { IWorkbenchPart::Pointer refPart = editorRefs[i]->GetPart(false); if (refPart != 0) { partsToClose.push_back(refPart); } } SaveablesList::Pointer modelManager; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (partsToClose.size() > 0) { modelManager = this->GetWorkbenchWindow()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast (); // this may prompt for saving and return 0 if the user canceled: postCloseInfo = modelManager->PreCloseParts(partsToClose, save, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { return false; } } // Fire pre-removal changes for (unsigned int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Notify interested listeners before the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_CLOSE); } this->DeferUpdates(true); try { if (modelManager != 0) { modelManager->PostClose(postCloseInfo); } // Close all editors. for (unsigned int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Remove editor from the presentation editorPresentation->CloseEditor(ref); this->PartRemoved(ref.Cast ()); } } catch (...) { } this->DeferUpdates(false); // Notify interested listeners after the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_CLOSE); // Return true on success. return true; } void WorkbenchPage::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferring(); } deferCount++; } else { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } void WorkbenchPage::StartDeferring() { //editorPresentation.getLayoutPart().deferUpdates(true); } void WorkbenchPage::HandleDeferredEvents() { editorPresentation->GetLayoutPart()->DeferUpdates(false); this->UpdateActivePart(); std::vector disposals = pendingDisposals; pendingDisposals.clear(); for (unsigned int i = 0; i < disposals.size(); i++) { this->DisposePart(disposals[i]); } } bool WorkbenchPage::IsDeferred() { return deferCount > 0; } bool WorkbenchPage::CloseEditor(IEditorReference::Pointer editorRef, bool save) { std::list list; list.push_back(editorRef); return this->CloseEditors(list, save); } bool WorkbenchPage::CloseEditor(IEditorPart::Pointer editor, bool save) { IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast ().IsNotNull()) { std::list list; list.push_back(ref.Cast ()); return this->CloseEditors(list, save); } return false; } void WorkbenchPage::ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) { Perspective::Pointer persp = this->FindPerspective(desc); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(Perspective::Pointer persp, bool saveParts, bool closePage) { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } std::vector partsToSave; std::list viewsToClose; // collect views that will go away and views that are dirty std::vector viewReferences = persp->GetViewReferences(); for (unsigned int i = 0; i < viewReferences.size(); i++) { IViewReference::Pointer reference = viewReferences[i]; if (this->GetViewFactory()->GetReferenceCount(reference) == 1) { IViewPart::Pointer viewPart = reference->GetView(false); if (viewPart != 0) { viewsToClose.push_back(viewPart); if (saveParts && reference->IsDirty()) { partsToSave.push_back(viewPart); } } } } if (saveParts && perspList.Size() == 1) { // collect editors that are dirty std::list editorReferences = this->GetEditorReferences(); for (std::list::iterator refIter = editorReferences.begin(); refIter != editorReferences.end(); ++refIter) { IEditorReference::Pointer reference = *refIter; if (reference->IsDirty()) { IEditorPart::Pointer editorPart = reference->GetEditor(false); if (editorPart != 0) { partsToSave.push_back(editorPart); } } } } if (saveParts && !partsToSave.empty()) { if (!EditorManager::SaveAll(partsToSave, true, true, false, IWorkbenchWindow::Pointer(window))) { // user canceled return; } } // Close all editors on last perspective close if (perspList.Size() == 1 && this->GetEditorManager()->GetEditorCount() > 0) { // Close all editors if (!this->CloseAllEditors(false)) { return; } } // closeAllEditors already notified the saveables list about the editors. SaveablesList::Pointer saveablesList = this->GetWorkbenchWindow()->GetWorkbench()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); // we took care of the saving already, so pass in false (postCloseInfo will be non-0) SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(viewsToClose, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); // Dispose of the perspective bool isActive = (perspList.GetActive() == persp); if (isActive) { this->SetPerspective(perspList.GetNextActive()); } this->DisposePerspective(persp, true); if (closePage && perspList.Size() == 0) { this->Close(); } } void WorkbenchPage::CloseAllPerspectives(bool saveEditors, bool closePage) { if (perspList.IsEmpty()) { return; } // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } if (saveEditors) { if (!this->SaveAllEditors(true)) { return; } } // Close all editors if (!this->CloseAllEditors(false)) { return; } // Deactivate the active perspective and part this->SetPerspective(Perspective::Pointer(0)); // Close each perspective in turn PerspectiveList oldList = perspList; perspList = PerspectiveList(); for (PerspectiveList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { this->ClosePerspective(*itr, false, false); } if (closePage) { this->Close(); } } void WorkbenchPage::CreateClientComposite() { void* parent = window->GetPageComposite(); // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() // { composite = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateClientComposite( parent); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); // Make visible on activate. // force the client composite to be layed out // parent.layout(); // } // }); } Perspective::Pointer WorkbenchPage::CreatePerspective( PerspectiveDescriptor::Pointer desc, bool notify) { std::string label = desc->GetId(); // debugging only try { //UIStats.start(UIStats.CREATE_PERSPECTIVE, label); WorkbenchPage::Pointer thisPage(this); Perspective::Pointer persp(new Perspective(desc, thisPage)); perspList.Add(persp); if (notify) { window->FirePerspectiveOpened(thisPage, desc); } //if the perspective is fresh and uncustomzied then it is not dirty //no reset will be prompted for if (!desc->HasCustomDefinition()) { dirtyPerspectives.erase(desc->GetId()); } return persp; } catch (WorkbenchException& /*e*/) { if (!window->GetWorkbenchImpl()->IsStarting()) { MessageDialog::OpenError(window->GetShell(), "Error", "Problems opening perspective \"" + desc->GetId() + "\""); } return Perspective::Pointer(0); } // finally // { // UIStats.end(UIStats.CREATE_PERSPECTIVE, desc.getId(), label); // } } void WorkbenchPage::PartAdded(WorkbenchPartReference::Pointer ref) { activationList->Add(ref); partList->AddPart(ref); this->UpdateActivePart(); } void WorkbenchPage::PartRemoved(WorkbenchPartReference::Pointer ref) { activationList->Remove(ref); this->DisposePart(ref); } void WorkbenchPage::DisposePart(WorkbenchPartReference::Pointer ref) { if (this->IsDeferred()) { pendingDisposals.push_back(ref); } else { partList->RemovePart(ref); ref->Dispose(); } } void WorkbenchPage::DeactivatePart(IWorkbenchPart::Pointer part) { if (part.IsNotNull()) { PartSite::Pointer site = part->GetSite().Cast (); site->GetPane()->ShowFocus(false); } } void WorkbenchPage::DetachView(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } PerspectiveHelper* presentation = persp->GetPresentation(); presentation->DetachPart(ref); } void WorkbenchPage::AttachView(IViewReference::Pointer ref) { PerspectiveHelper* presentation = this->GetPerspectivePresentation(); presentation->AttachPart(ref); } WorkbenchPage::~WorkbenchPage() { // increment reference count to prevent recursive deletes this->Register(); { { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); // Close and dispose the editors. this->CloseAllEditors(false); // Need to make sure model data is cleaned up when the page is // disposed. Collect all the views on the page and notify the // saveable list of a pre/post close. This will free model data. std::vector partsToClose = this->GetOpenParts(); std::list dirtyParts; for (unsigned int i = 0; i < partsToClose.size(); i++) { IWorkbenchPart::Pointer part = partsToClose[i]->GetPart(false); if (part != 0 && part.Cast () != 0) { dirtyParts.push_back(part); } } SaveablesList::Pointer saveablesList = this->GetWorkbenchWindow()->GetWorkbench()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(dirtyParts, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); IWorkbenchPage::Pointer thisPage(this); // Get rid of perspectives. This will close the views for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer perspective = *itr; window->FirePerspectiveClosed(thisPage, perspective->GetDesc()); //perspective->Dispose(); } perspList = PerspectiveList(); // Capture views. std::vector refs = viewFactory->GetViews(); // if (refs.size() > 0) // { // // Dispose views. // for (unsigned int i = 0; i < refs.size(); i++) // { // WorkbenchPartReference::Pointer ref = refs[i].Cast(); // //partList.RemovePart(ref); // //this->FirePartClosed(refs[i]); // // Platform.run(new SafeRunnable() { // // public void run() { // // // WorkbenchPlugin.log(new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // // // Status.OK, "WorkbenchPage leaked a refcount for view " + ref.getId(), 0)); //$NON-NLS-1$//$NON-NLS-2$ // // ref.dispose(); // // } // // // public void handleException(Throwable e) { // // } // // }); // } // } // Get rid of editor presentation. //editorPresentation->Dispose(); // Get rid of composite. //composite.dispose(); //navigationHistory.dispose(); //stickyViewMan.clear(); // if (tracker != 0) // { // tracker.close(); // } // // if we're destroying a window in a non-shutdown situation then we should // // clean up the working set we made. // if (!window->GetWorkbench()->IsClosing()) // { // if (aggregateWorkingSet != 0) // { // PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet( // aggregateWorkingSet); // } // } } partBeingActivated = 0; pendingDisposals.clear(); stickyViewMan = 0; delete viewFactory; delete editorPresentation; delete editorMgr; delete activationList; deferredActivePersp = 0; dirtyPerspectives.clear(); delete selectionService; partList = 0; } // decrement reference count again, without explicit deletion this->UnRegister(false); } void WorkbenchPage::DisposePerspective(Perspective::Pointer persp, bool notify) { // Get rid of perspective. perspList.Remove(persp); if (notify) { IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveClosed(thisPage, persp->GetDesc()); } //persp->Dispose(); stickyViewMan->Remove(persp->GetDesc()->GetId()); } Perspective::Pointer WorkbenchPage::FindPerspective( IPerspectiveDescriptor::Pointer desc) { for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer mgr = *itr; if (desc->GetId() == mgr->GetDesc()->GetId()) { return mgr; } } return Perspective::Pointer(0); } IViewPart::Pointer WorkbenchPage::FindView(const std::string& id) { IViewReference::Pointer ref = this->FindViewReference(id); if (ref == 0) { return IViewPart::Pointer(0); } return ref->GetView(true); } IViewReference::Pointer WorkbenchPage::FindViewReference( const std::string& viewId) { return this->FindViewReference(viewId, ""); } IViewReference::Pointer WorkbenchPage::FindViewReference( const std::string& viewId, const std::string& secondaryId) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewReference::Pointer(0); } return persp->FindView(viewId, secondaryId); } IEditorPart::Pointer WorkbenchPage::GetActiveEditor() { return partList->GetActiveEditor(); } IEditorReference::Pointer WorkbenchPage::GetActiveEditorReference() { return partList->GetActiveEditorReference(); } IWorkbenchPart::Pointer WorkbenchPage::GetActivePart() { return partList->GetActivePart(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetActivePartReference() { return partList->GetActivePartReference(); } Perspective::Pointer WorkbenchPage::GetActivePerspective() { return perspList.GetActive(); } void* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } std::vector WorkbenchPage::GetEditors() { std::list refs = this->GetEditorReferences(); std::vector result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (std::list::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } std::vector WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } std::vector WorkbenchPage::GetDirtyParts() { std::vector result; std::vector allParts = this->GetAllParts(); for (unsigned int i = 0; i < allParts.size(); i++) { IWorkbenchPartReference::Pointer reference = allParts[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0 && part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty()) { result.push_back(saveable); } } } return result; } IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input) { return this->GetEditorManager()->FindEditor(input); } std::vector WorkbenchPage::FindEditors( IEditorInput::Pointer input, const std::string& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } std::list WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } std::string WorkbenchPage::GetLabel() { std::string label = ""; // IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input, // IWorkbenchAdapter.class); // if (adapter != 0) // { // label = adapter.getLabel(input); // } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { label = label + " - " + persp->GetDesc()->GetLabel(); } else if (deferredActivePersp != 0) { label = label + " - " + deferredActivePersp->GetLabel(); } return label; } IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective() { if (deferredActivePersp != 0) { return deferredActivePersp; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetDesc(); } else { return IPerspectiveDescriptor::Pointer(0); } } ISelection::ConstPointer WorkbenchPage::GetSelection() const { return selectionService->GetSelection(); } ISelection::ConstPointer WorkbenchPage::GetSelection(const std::string& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const std::string& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } std::vector WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return std::vector(); } } std::vector WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } std::vector WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } std::vector parts; if (persp != 0) { std::vector refs = persp->GetViewReferences(); for (unsigned int i = 0; i < refs.size(); i++) { IViewPart::Pointer part = refs[i]->GetPart(restore).Cast (); if (part != 0) { parts.push_back(part); } } } return parts; } IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() { return IWorkbenchWindow::Pointer(window); } void WorkbenchPage::HideView(IViewReference::Pointer ref) { // Sanity check. if (ref == 0) { return; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } bool promptedForSave = false; IViewPart::Pointer view = ref->GetView(false); if (view != 0) { if (!this->CertifyPart(view)) { return; } // Confirm. if (view.Cast () != 0) { ISaveablePart::Pointer saveable = view.Cast (); if (saveable->IsSaveOnCloseNeeded()) { IWorkbenchWindow::Pointer window = view->GetSite()->GetWorkbenchWindow(); std::vector partsToSave; partsToSave.push_back(view); bool success = EditorManager::SaveAll(partsToSave, true, true, false, window); if (!success) { // the user cancelled. return; } promptedForSave = true; } } } int refCount = this->GetViewFactory()->GetReferenceCount(ref); SaveablesList::Pointer saveablesList; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = actualPart->GetSite()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); std::list partsToClose; partsToClose.push_back(actualPart); postCloseInfo = saveablesList->PreCloseParts(partsToClose, !promptedForSave, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { // cancel return; } } } IWorkbenchPage::Pointer thisPage(this); // Notify interested listeners before the hide window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref, CHANGE_VIEW_HIDE); PartPane::Pointer pane = this->GetPane(ref.Cast ()); pane->SetInLayout(false); this->UpdateActivePart(); if (saveablesList != 0) { saveablesList->PostClose(postCloseInfo); } // Hide the part. persp->HideView(ref); // Notify interested listeners after the hide window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_VIEW_HIDE); } void WorkbenchPage::RefreshActiveView() { this->UpdateActivePart(); } void WorkbenchPage::HideView(IViewPart::Pointer view) { this->HideView(this->GetReference(view).Cast ()); } void WorkbenchPage::Init(WorkbenchWindow* w, const std::string& layoutID, IAdaptable* input, bool openExtras) { // Save args. this->window = w; this->input = input; this->composite = 0; this->viewFactory = 0; this->activationList = new ActivationList(this); this->selectionService = new PageSelectionService(this); this->partList = new WorkbenchPagePartList(this->selectionService); this->stickyViewMan = new StickyViewManager(this); //actionSets = new ActionSetManager(w); deferCount = 0; // Create presentation. this->CreateClientComposite(); editorPresentation = new EditorAreaHelper(this); editorMgr = new EditorManager(WorkbenchWindow::Pointer(window), WorkbenchPage::Pointer(this), editorPresentation); //TODO WorkbenchPage perspective reorder listener? // // add this page as a client to be notified when the UI has re-ordered perspectives // // so that the order can be properly maintained in the receiver. // // E.g. a UI might support drag-and-drop and will need to make this known to ensure // // #saveState and #restoreState do not lose this re-ordering // w.addPerspectiveReorderListener(new IReorderListener() // { // public void WorkbenchPage::reorder(Object perspective, int newLoc) // { // perspList.reorder((IPerspectiveDescriptor)perspective, newLoc); // } // }); if (openExtras) { this->OpenPerspectiveExtras(); } // Get perspective descriptor. if (layoutID != "") { PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( layoutID).Cast (); if (desc == 0) { throw WorkbenchException("Unable to create Perspective " + layoutID + ". There is no corresponding perspective extension."); } Perspective::Pointer persp = this->FindPerspective(desc); if (persp == 0) { persp = this->CreatePerspective(desc, true); } perspList.SetActive(persp); window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc); } // getExtensionTracker() .registerHandler(perspectiveChangeHandler, // ExtensionTracker .createExtensionPointFilter( // getPerspectiveExtensionPoint())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras std::string extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); Poco::StringTokenizer tok(extras, ", ", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); //$NON-NLS-1$ std::vector descs; for (Poco::StringTokenizer::Iterator itr = tok.begin(); itr != tok.end(); ++itr) { std::string id = *itr; IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( id); if (desc != 0) { descs.push_back(desc); } } // HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list. // So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared. for (int i = (int) descs.size(); --i >= 0;) { PerspectiveDescriptor::Pointer desc = descs[i].Cast (); if (this->FindPerspective(desc) == 0) { this->CreatePerspective(desc, true); } } } bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); return pane != 0 && pane->GetVisible(); } bool WorkbenchPage::IsEditorAreaVisible() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return false; } return persp->IsEditorAreaVisible(); } bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { //return persp->IsFastView(ref); return false; } else { return false; } } bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsCloseable(ref); } return false; } bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsMoveable(ref); } return false; } bool WorkbenchPage::IsFixedLayout() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsFixedLayout(); } else { return false; } } bool WorkbenchPage::IsSaveNeeded() { return this->GetEditorManager()->IsSaveAllNeeded(); } void WorkbenchPage::OnActivate() { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true); Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->OnActivate(); this->UpdateVisibility(Perspective::Pointer(0), persp); } } void WorkbenchPage::OnDeactivate() { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); if (this->GetActivePerspective() != 0) { this->GetActivePerspective()->OnDeactivate(); } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); } void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) { // Rather than calling editor.setInput on the editor directly, we do it through the part reference. // This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response // to the input change... but if all editors obeyed their API contract, the "else" branch would be // sufficient. IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast () != 0) { EditorReference::Pointer editorRef = ref.Cast (); editorRef->SetInput(input); } else { editor->SetInput(input); } //navigationHistory.markEditor(editor); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const std::string& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const std::string& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const std::string& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const std::string& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { if (input == 0 || editorID == "") { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditor(input, editorID, activate, matchFlags, editorState); } IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor( IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { if (input == 0 || !(editorDescriptor.Cast () != 0)) { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast< EditorDescriptor> (), activate, editorState); // } // }); } IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input, const std::string& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor, activate, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched( IEditorInput::Pointer input, const std::string& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { // If an editor already exists for the input, use it. IEditorPart::Pointer editor; // Reuse an existing open editor, unless we are in "new editor tab management" mode editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags); if (editor != 0) { if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID) { if (editor->IsDirty()) { std::vector dlgLabels; dlgLabels.push_back("Yes"); dlgLabels.push_back("No"); dlgLabels.push_back("Cancel"); IDialog::Pointer dialog = MessageDialog::CreateMessageDialog( this->GetWorkbenchWindow()->GetShell(), "Save", (void*) 0, // accept the default window icon "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", IDialog::QUESTION, dlgLabels, 0); int saveFile = dialog->Open(); if (saveFile == 0) { // try // { IEditorPart::Pointer editorToSave = editor; // getWorkbenchWindow().run(false, false, // new IRunnableWithProgress() // { // public void WorkbenchPage::run(IProgressMonitor monitor) // throws InvocationTargetException, // InterruptedException // { //TODO progress monitor editorToSave->DoSave();//monitor); // } // }); // } // catch (InvocationTargetException& e) // { // throw(RuntimeException) e->GetTargetException(); // } // catch (InterruptedException& e) // { // return 0; // } } else if (saveFile == 2) { return IEditorPart::Pointer(0); } } } else { // // do the IShowEditorInput notification before showing the editor // // to reduce flicker // if (editor.Cast () != 0) // { // ((IShowEditorInput) editor).showEditorInput(input); // } this->ShowEditor(activate, editor); return editor; } } // Otherwise, create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor( editorID, input, true, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { IEditorPart::Pointer editor; // Create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor, input, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } void WorkbenchPage::OpenEmptyTab() { IEditorPart::Pointer editor; EditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEmptyTab().Cast (); if (ref != 0) { editor = ref->GetEmptyEditor( dynamic_cast (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor( EditorRegistry::EMPTY_EDITOR_ID).Cast ()); } if (editor != 0) { this->SetEditorAreaVisible(true); this->Activate(editor); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } } void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor) { this->SetEditorAreaVisible(true); if (activate) { //zoomOutIfNecessary(editor); this->Activate(editor); } else { this->BringToTop(editor); } } bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor) { WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast< WorkbenchPartReference> (); return ref != 0 && ref->IsPinned(); } /** * Removes an IPartListener from the part service. */ void WorkbenchPage::RemovePartListener(IPartListener::Pointer l) { partList->GetPartService()->RemovePartListener(l); } /** * Implements IWorkbenchPage * * @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener) * @since 2.0 * @deprecated individual views should store a working set if needed and * register a property change listener directly with the * working set manager to receive notification when the view * working set is removed. */ // void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) { // propertyChangeListeners.remove(listener); // } void WorkbenchPage::RemoveSelectionListener( ISelectionListener::Pointer listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener( ISelectionListener::Pointer listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->RemovePostSelectionListener(partId, listener); } void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } // Real work. this->SetActivePart(part); } /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ void WorkbenchPage::ResetPerspective() { // Run op in busy cursor. // Use set redraw to eliminate the "flash" that can occur in the // coolbar as the perspective is reset. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // try // { // mgr.getControl2().setRedraw(false); // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusyResetPerspective(); // } // }); // }finally // { // mgr.getControl2().setRedraw(true); // } } bool WorkbenchPage::RestoreState(IMemento::Pointer memento, const IPerspectiveDescriptor::Pointer activeDescriptor) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { this->DeferUpdates(true); // }}); try { // Restore working set std::string pageName; memento->GetString(WorkbenchConstants::TAG_LABEL, pageName); // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH)) // { // label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$ // } try { //UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$ // MultiStatus result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToRestorePerspective, // pageName), 0); bool result = true; // String workingSetName = memento .getString( // IWorkbenchConstants.TAG_WORKING_SET); // if (workingSetName != 0) // { // AbstractWorkingSetManager // workingSetManager = // (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager(); // setWorkingSet(workingSetManager.getWorkingSet(workingSetName)); // } // // IMemento workingSetMem = memento .getChild( // IWorkbenchConstants.TAG_WORKING_SETS); // if (workingSetMem != 0) // { // std::vector workingSetChildren = // workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET); // List workingSetList = new ArrayList(workingSetChildren.length); // for (int i = 0; i < workingSetChildren.length; i++) // { // IWorkingSet // set = // getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet( // workingSetChildren[i].getID()); // if (set != 0) // { // workingSetList.add(set); // } // } // // workingSets = (IWorkingSet[]) workingSetList .toArray( // new IWorkingSet[workingSetList.size()]); // } // // aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID); // // IWorkingSet setWithId = // window.getWorkbench().getWorkingSetManager().getWorkingSet( // aggregateWorkingSetId); // // // check to see if the set has already been made and assign it if it has // if (setWithId.Cast () != 0) // { // aggregateWorkingSet = (AggregateWorkingSet) setWithId; // } // Restore editor manager. IMemento::Pointer childMem = memento->GetChild( WorkbenchConstants::TAG_EDITORS); //result.merge(getEditorManager().restoreState(childMem)); result &= this->GetEditorManager()->RestoreState(childMem); childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS); if (childMem) { //result.merge(getViewFactory().restoreState(childMem)); result &= this->GetViewFactory()->RestoreState(childMem); } // Get persp block. childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES); std::string activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); std::string activePartSecondaryID; if (!activePartID.empty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.empty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } std::string activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. std::vector perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; for (std::size_t i = 0; i < perspMems.size(); i++) { IMemento::Pointer current = perspMems[i]; // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { Perspective::Pointer persp(new Perspective( PerspectiveDescriptor::Pointer(0), WorkbenchPage::Pointer(this))); //result.merge(persp.restoreState(current)); result &= persp->RestoreState(current); IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc); // } // }); } bool restoreActivePerspective = false; if (!activeDescriptor) { restoreActivePerspective = true; } else if (activePerspective && activePerspective->GetDesc() == activeDescriptor) { restoreActivePerspective = true; } else { restoreActivePerspective = false; activePerspective = this->CreatePerspective(activeDescriptor.Cast< PerspectiveDescriptor> (), true); if (activePerspective == 0) { // result .merge( // new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.Workbench_showPerspectiveError, // activeDescriptor.getId()), 0)); result &= false; } } perspList.SetActive(activePerspective); // Make sure we have a valid perspective to work with, // otherwise return. activePerspective = perspList.GetActive(); if (activePerspective == 0) { activePerspective = perspList.GetNextActive(); perspList.SetActive(activePerspective); } if (activePerspective && restoreActivePerspective) { //result.merge(activePerspective.restoreState()); result &= activePerspective->RestoreState(); } if (activePerspective) { Perspective::Pointer myPerspective = activePerspective; std::string myActivePartId = activePartID; std::string mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.empty()) { IWorkbenchPartReference::Pointer ref = myPerspective->FindView( myActivePartId, mySecondaryId); if (ref) { activationList->SetActive(ref); } } // }}); } // childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY); // if (childMem) // { // navigationHistory.restoreState(childMem); // } // else if (GetActiveEditor()) // { // navigationHistory.markEditor(getActiveEditor()); // } // // restore sticky view state stickyViewMan->Restore(memento); // std::string blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); return result; } catch (...) { // std::string blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ throw ; } } catch (...) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); throw; } } bool WorkbenchPage::SaveAllEditors(bool confirm) { return this->SaveAllEditors(confirm, false); } bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources) { return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources); } bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm) { // Do not certify part do allow editors inside a multipageeditor to // call this. return this->GetEditorManager()->SavePart(saveable, part, confirm); } bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm) { return this->SavePart(editor, editor, confirm); } /** * Saves the current perspective. */ void WorkbenchPage::SavePerspective() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDesc(); } /** * Saves the perspective. */ void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc(); // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDescAs(newDesc); window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc); } /** * Save the state of the page. */ bool WorkbenchPage::SaveState(IMemento::Pointer memento) { // // We must unzoom to get correct layout. // if (isZoomed()) // { // zoomOut(); // } // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToSavePerspective, // getLabel()), 0); bool result = true; // Save editor manager. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS); //result.merge(editorMgr.saveState(childMem)); result &= editorMgr->SaveState(childMem); childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS); //result.merge(getViewFactory().saveState(childMem)); result &= this->GetViewFactory()->SaveState(childMem); // Create persp block. childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES); if (this->GetPerspective()) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, this->GetPerspective()->GetId()); } if (this->GetActivePart() != 0) { if (this->GetActivePart().Cast ()) { IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast(); if (ref) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, ViewFactory::GetKey(ref)); } } else { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, this->GetActivePart()->GetSite()->GetId()); } } // Save each perspective in opened order for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { IMemento::Pointer gChildMem = childMem->CreateChild( WorkbenchConstants::TAG_PERSPECTIVE); //result.merge(persp.saveState(gChildMem)); result &= (*itr)->SaveState(gChildMem); } // // Save working set if set // if (workingSet != 0) // { // memento.putString(IWorkbenchConstants.TAG_WORKING_SET, // workingSet .getName()); // } // // IMemento workingSetMem = memento .createChild( // IWorkbenchConstants.TAG_WORKING_SETS); // for (int i = 0; i < workingSets.length; i++) // { // workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET, // workingSets[i].getName()); // } // // if (aggregateWorkingSetId != 0) // { // memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId); // } // // navigationHistory.saveState(memento .createChild( // IWorkbenchConstants.TAG_NAVIGATION_HISTORY)); // // save the sticky activation state stickyViewMan->Save(memento); return result; } std::string WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } std::string WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { return "0"; //$NON-NLS-1$ } return ref->GetId(); } void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize it. if (this->GetActivePart() == newPart) { return; } if (partBeingActivated != 0) { if (partBeingActivated->GetPart(false) != newPart) { WorkbenchPlugin::Log(Poco::RuntimeException( "WARNING: Prevented recursive attempt to activate part " + this->GetId(newPart) + " while still in the middle of activating part " + this->GetId( partBeingActivated))); } return; } //No need to change the history if the active editor is becoming the // active part // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.ACTIVATE_PART)) // { // label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$ // } try { IWorkbenchPartReference::Pointer partref = this->GetReference(newPart); IWorkbenchPartReference::Pointer realPartRef; if (newPart != 0) { IWorkbenchPartSite::Pointer site = newPart->GetSite(); if (site.Cast () != 0) { realPartRef = site.Cast ()->GetPane()->GetPartReference(); } } partBeingActivated = realPartRef; //UIStats.start(UIStats.ACTIVATE_PART, label); // Notify perspective. It may deactivate fast view. Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->PartActivated(newPart); } // Deactivate old part IWorkbenchPart::Pointer oldPart = this->GetActivePart(); if (oldPart != 0) { this->DeactivatePart(oldPart); } // Set active part. if (newPart != 0) { activationList->SetActive(newPart); if (newPart.Cast () != 0) { this->MakeActiveEditor(realPartRef.Cast ()); } } this->ActivatePart(newPart); actionSwitcher.UpdateActivePart(newPart); partList->SetActivePart(partref); } catch (std::exception& e) { partBeingActivated = 0; // Object blame = newPart == 0 ? (Object) this : newPart; // UIStats.end(UIStats.ACTIVATE_PART, blame, label); throw e; } partBeingActivated = 0; } void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } if (showEditorArea == persp->IsEditorAreaVisible()) { return; } // // If parts change always update zoom. // if (isZoomed()) // { // zoomOut(); // } // Update editor area visibility. IWorkbenchPage::Pointer thisPage(this); if (showEditorArea) { persp->ShowEditorArea(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_SHOW); } else { persp->HideEditorArea(); this->UpdateActivePart(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_HIDE); } } /** * Sets the layout of the page. Assumes the new perspective is not 0. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp) { // Don't do anything if already active layout Perspective::Pointer oldPersp = this->GetActivePerspective(); if (oldPersp == newPersp) { return; } window->LargeUpdateStart(); std::exception exc; bool exceptionOccured = false; try { IWorkbenchPage::Pointer thisPage(this); if (oldPersp != 0) { // fire the pre-deactivate window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc()); } if (newPersp != 0) { bool status = newPersp->RestoreState(); if (!status) { std::string title = "Restoring problems"; std::string msg = "Unable to read workbench state."; MessageDialog::OpenError(this->GetWorkbenchWindow()->GetShell(), title, msg); } } // Deactivate the old layout if (oldPersp != 0) { oldPersp->OnDeactivate(); // Notify listeners of deactivation window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc()); } // Activate the new layout perspList.SetActive(newPersp); if (newPersp != 0) { newPersp->OnActivate(); // Notify listeners of activation window->FirePerspectiveActivated(thisPage, newPersp->GetDesc()); } this->UpdateVisibility(oldPersp, newPersp); // Update the window //TODO action sets //window->UpdateActionSets(); // Update sticky views stickyViewMan->Update(oldPersp, newPersp); } catch (std::exception& e) { exc = e; exceptionOccured = true; } window->LargeUpdateEnd(); if (newPersp == 0) { return; } IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc(); if (desc == 0) { return; } if (dirtyPerspectives.erase(desc->GetId())) { this->SuggestReset(); } if (exceptionOccured) throw exc; } void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp, Perspective::Pointer newPersp) { // Flag all parts in the old perspective std::vector oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (unsigned int i = 0; i < oldRefs.size(); i++) { PartPane::Pointer pane = oldRefs[i].Cast ()->GetPane(); pane->SetInLayout(false); } } PerspectiveHelper* pres = 0; // Make parts in the new perspective visible if (newPersp != 0) { pres = newPersp->GetPresentation(); std::vector newRefs = newPersp->GetViewReferences(); for (unsigned int i = 0; i < newRefs.size(); i++) { WorkbenchPartReference::Pointer ref = newRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres->IsPartVisible(ref)) { activationList->BringToTop(ref); } pane->SetInLayout(true); } } this->UpdateActivePart(); // Hide any parts in the old perspective that are no longer visible for (unsigned int i = 0; i < oldRefs.size(); i++) { WorkbenchPartReference::Pointer ref = oldRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres == 0 || !pres->IsPartVisible(ref)) { pane->SetVisible(false); } } } /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc) { if (this->GetPerspective() == desc) { return; } // // Going from multiple to single rows can make the coolbar // // and its adjacent views appear jumpy as perspectives are // // switched. Turn off redraw to help with this. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); std::exception exc; bool exceptionOccured = false; try { //mgr.getControl2().setRedraw(false); //getClientComposite().setRedraw(false); // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusySetPerspective(desc); // } // }); } catch (std::exception& e) { exc = e; exceptionOccured = true; } // getClientComposite().setRedraw(true); // mgr.getControl2().setRedraw(true); IWorkbenchPart::Pointer part = this->GetActivePart(); if (part != 0) { part->SetFocus(); } if (exceptionOccured) throw exc; } PartService* WorkbenchPage::GetPartService() { return dynamic_cast (partList->GetPartService()); } void WorkbenchPage::ResetToolBarLayout() { // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // mgr.resetItemOrder(); } IViewPart::Pointer WorkbenchPage::ShowView(const std::string& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const std::string& viewID, const std::string& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.find_first_of( ViewFactory::ID_SEP) != std::string::npos) { throw Poco::InvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw Poco::InvalidArgumentException("Illegal view mode"); } // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { // try // { return this->BusyShowView(viewID, secondaryID, mode); // } catch (PartInitException& e) // { // result = e; // } // } // }); } bool WorkbenchPage::CertifyMode(int mode) { if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE) return true; return false; } std::vector WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } std::vector WorkbenchPage::GetOpenPerspectives() { std::list opened = perspList.GetOpenedPerspectives(); std::vector result; for (std::list::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } std::list WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { std::list perspectives = perspList.GetSortedPerspectives(); for (std::list::reverse_iterator iter = perspectives.rbegin(); iter != perspectives.rend(); ++iter) { if ((*iter)->ContainsView(part)) { return *iter; } } // we should never get here return Perspective::Pointer(0); } std::vector WorkbenchPage::GetSortedPerspectives() { std::list sortedArray = perspList.GetSortedPerspectives(); std::vector result; for (std::list::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } std::vector WorkbenchPage::GetSortedParts() { //return partList->GetParts(this->GetViewReferences()); return activationList->GetParts(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetReference( IWorkbenchPart::Pointer part) { if (part == 0) { return IWorkbenchPartReference::Pointer(0); } IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } PartSite::Pointer partSite = site.Cast (); PartPane::Pointer pane = partSite->GetPane(); return partSite->GetPartReference(); } // for dynamic UI void WorkbenchPage::AddPerspective(Perspective::Pointer persp) { perspList.Add(persp); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveOpened(thisPage, persp->GetDesc()); } std::vector WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return std::vector(); } IStackableContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); std::vector list; IStackableContainer::ChildrenType children = folder->GetChildren(); for (IStackableContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { StackablePart::Pointer stackablePart = *childIter; if (stackablePart.Cast () != 0) { IViewReference::Pointer view = stackablePart.Cast ()->GetPartReference().Cast< IViewReference> (); if (view != 0) { list.push_back(view); } } } // sort the list by activation order (most recently activated first) std::sort(list.begin(), list.end(), ActivationOrderPred(activationList)); return list; } std::vector result; result.push_back(this->GetReference(part).Cast ()); return result; } std::vector WorkbenchPage::GetViewStack( IViewPart::Pointer part) { std::vector refStack = this->GetViewReferenceStack( part); std::vector result; for (unsigned int i = 0; i < refStack.size(); i++) { IViewPart::Pointer next = refStack[i]->GetView(false); if (next != 0) { result.push_back(next); } } return result; } void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height) { SashInfo sashInfo; PartPane::Pointer pane = part->GetSite().Cast ()->GetPane(); IStackableContainer::Pointer container = pane->GetContainer(); LayoutTree::Pointer tree = this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find( container.Cast ()); // retrieve our layout sashes from the layout tree this->FindSashParts(tree, pane->FindSashes(), sashInfo); // first set the width int deltaWidth = width - pane->GetBounds().width; if (sashInfo.right != 0) { Rectangle rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x) - rightBounds.x) / rightBounds.width); // complete the resize sashInfo.rightNode->SetBounds(rightBounds); } else if (sashInfo.left != 0) { Rectangle leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x - deltaWidth) - leftBounds.x) / leftBounds.width); // complete the resize sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds()); } // next set the height int deltaHeight = height - pane->GetBounds().height; if (sashInfo.bottom != 0) { Rectangle bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y) - bottomBounds.y) / bottomBounds.height); // complete the resize sashInfo.bottomNode->SetBounds(bottomBounds); } else if (sashInfo.top != 0) { Rectangle topBounds = sashInfo.topNode->GetBounds(); // set the ratio sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y - deltaHeight) - topBounds.y) / topBounds.height); // complete the resize sashInfo.topNode->SetBounds(topBounds); } } void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree, const PartPane::Sashes& sashes, SashInfo& info) { LayoutTree::Pointer parent(tree->GetParent()); if (parent == 0) { return; } if (parent->part.Cast () != 0) { // get the layout part sash from this tree node LayoutPartSash::Pointer sash = parent->part.Cast (); // make sure it has a sash control void* control = sash->GetControl(); if (control != 0) { // check for a vertical sash if (sash->IsVertical()) { if (sashes.left == control) { info.left = sash; info.leftNode = parent->FindSash(sash); } else if (sashes.right == control) { info.right = sash; info.rightNode = parent->FindSash(sash); } } // check for a horizontal sash else { if (sashes.top == control) { info.top = sash; info.topNode = parent->FindSash(sash); } else if (sashes.bottom == control) { info.bottom = sash; info.bottomNode = parent->FindSash(sash); } } } } // recursive call to continue up the tree this->FindSashParts(parent, sashes, info); } std::vector WorkbenchPage::GetAllParts() { std::vector views = viewFactory->GetViews(); std::list editors = this->GetEditorReferences(); std::vector result; for (unsigned int i = 0; i < views.size(); i++) { result.push_back(views[i]); } for (std::list::iterator iter = editors.begin(); iter != editors.end(); ++iter) { result.push_back(*iter); } return result; } std::vector WorkbenchPage::GetOpenParts() { std::vector refs = this->GetAllParts(); std::vector result; for (unsigned int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0) { result.push_back(reference); } } return result; } void WorkbenchPage::TestInvariants() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->TestInvariants(); // When we have widgets, ensure that there is no situation where the editor area is visible // and the perspective doesn't want an editor area. if (this->GetClientComposite() && editorPresentation->GetLayoutPart()->IsVisible()) { poco_assert(persp->IsEditorAreaVisible()); } } } /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() */ // IExtensionTracker WorkbenchPage::GetExtensionTracker() // { // if (tracker == 0) // { // tracker = new UIExtensionTracker(getWorkbenchWindow().getWorkbench().getDisplay()); // } // return tracker; // } /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ std::vector WorkbenchPage::GetPerspectiveShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return std::vector(); } return persp->GetPerspectiveShortcuts(); } std::vector WorkbenchPage::GetShowViewShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return std::vector(); } return persp->GetShowViewShortcuts(); } void WorkbenchPage::SuggestReset() { IWorkbench* workbench = this->GetWorkbenchWindow()->GetWorkbench(); // workbench.getDisplay().asyncExec(new Runnable() // { // public void WorkbenchPage::run() // { Shell::Pointer parentShell; IWorkbenchWindow::Pointer window = workbench->GetActiveWorkbenchWindow(); if (window == 0) { if (workbench->GetWorkbenchWindowCount() == 0) { return; } window = workbench->GetWorkbenchWindows()[0]; } parentShell = window->GetShell(); if (MessageDialog::OpenQuestion(parentShell, "Reset Perspective?", "Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?")) { IWorkbenchPage::Pointer page = window->GetActivePage(); if (page == 0) { return; } page->ResetPerspective(); } // } // }); } bool WorkbenchPage::IsPartVisible( IWorkbenchPartReference::Pointer reference) { IWorkbenchPart::Pointer part = reference->GetPart(false); // Can't be visible if it isn't created yet if (part == 0) { return false; } return this->IsPartVisible(part); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h index d8e119a7e3..e7c4b85502 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h @@ -1,70 +1,68 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYDNDTWEAKLET_H_ #define BERRYDNDTWEAKLET_H_ #include #include #include "../internal/berryTweaklets.h" namespace berry { struct ITracker; /** * Provides the set of cursors used for drag-and-drop. */ -struct BERRY_UI DnDTweaklet : public Object +struct BERRY_UI DnDTweaklet { - berryInterfaceMacro(DnDTweaklet, berry); - static Tweaklets::TweakKey KEY; enum CursorType { CURSOR_INVALID, CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER, CURSOR_OFFSCREEN, CURSOR_FASTVIEW}; static CursorType PositionToCursorType(int positionConstant); /** * Converts a DnDTweaklet::CursorType (CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER) into a BlueBerry constant * (Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM, Constants::CENTER) * * @param dragCursorId * @return a BlueBerry Constants::* constant */ static int CursorTypeToPosition(CursorType dragCursorId); virtual ITracker* CreateTracker() = 0; }; } Q_DECLARE_INTERFACE(berry::DnDTweaklet, "org.blueberry.DnDTweaklet") #endif /* BERRYDNDTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h index 39482b49dc..1fd16f42e6 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h @@ -1,215 +1,214 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYGUIWIDGETSTWEAKLET_H_ #define BERRYGUIWIDGETSTWEAKLET_H_ #include #include "../internal/berryTweaklets.h" #include "../guitk/berryGuiTkISelectionListener.h" #include "../guitk/berryGuiTkIControlListener.h" #include "../berryRectangle.h" #include "../berryShell.h" //#include "../commands/berryIMenu.h" //#include "../commands/berryIMenuItem.h" namespace berry { -struct BERRY_UI GuiWidgetsTweaklet : public Object +struct BERRY_UI GuiWidgetsTweaklet { - berryInterfaceMacro(GuiWidgetsTweaklet, berry); static Tweaklets::TweakKey KEY; virtual void AddSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; virtual void RemoveSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; /** * Adds the listener to the collection of listeners who will * be notified when the widget is moved or resized, by sending * it one of the messages defined in the IControlListener * interface. * * @param listener the listener which should be notified * * @see IControlListener * @see #RemoveControlListener */ virtual void AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; /** * Removes the listener from the collection of listeners who will * be notified when the widget is moved or resized. * * @param listener the listener which should no longer be notified * * @see IControlListener * @see #AddControlListener */ virtual void RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; virtual bool GetEnabled(void* widget) = 0; virtual void SetEnabled(void* widget, bool enabled) = 0; virtual void SetBounds(void* widget, const Rectangle& bounds) = 0; virtual Rectangle GetBounds(void* widget) = 0; virtual void SetVisible(void* widget, bool visible) = 0; virtual bool GetVisible(void* widget) = 0; virtual bool IsVisible(void* widget) = 0; virtual Rectangle GetClientArea(void* widget) = 0; virtual void* GetParent(void* widget) = 0; virtual bool SetParent(void* widget, void* parent) = 0; virtual void SetData(void* widget, const std::string& id, Object::Pointer data) = 0; virtual Object::Pointer GetData(void* widget, const std::string& id) = 0; virtual Point GetCursorLocation() = 0; virtual void* GetCursorControl() = 0; virtual void* FindControl(const std::vector& shells, const Point& location) = 0; /** * Determines if one control is a child of another. Returns true iff the second * argument is a child of the first (or the same object). * * @param potentialParent * @param childToTest * @return */ virtual bool IsChild(void* potentialParent, void* childToTest) = 0; /** * Returns the control which currently has keyboard focus, * or null if keyboard events are not currently going to * any of the controls built by the currently running * application. * * @return the control under the cursor */ virtual void* GetFocusControl() = 0; virtual bool IsReparentable(void* widget) = 0; virtual void MoveAbove(void* widgetToMove, void* widget) = 0; virtual void MoveBelow(void* widgetToMove, void* widget) = 0; virtual void Dispose(void* widget) = 0; virtual Shell::Pointer CreateShell(Shell::Pointer parent, int style) = 0; virtual void DisposeShell(Shell::Pointer shell) = 0; virtual void* CreateComposite(void* parent) = 0; virtual std::vector GetShells() = 0; virtual Shell::Pointer GetShell(void* widget) = 0; virtual Shell::Pointer GetActiveShell() = 0; // command framework interface classes //virtual IMenu::Pointer CreateMenu(void*, IMenu::Style = IMenu::POP_UP) = 0; //virtual IMenu::Pointer CreateMenu(IMenu::Pointer parent) = 0; //virtual IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1) = 0; /** * @brief returns the coordinates of the center point of the primary screen * (where the application starts) of the current desktop. * * @param i the number of the screen (if there are multiple). If i = -1 * a rectangle representing the size of the virtual desktop is returned. * @return the screen Geometry. * @see GetScreenNumber() * @see GetPrimaryScreenNumber() */ virtual Rectangle GetScreenSize(int i = -1) = 0; virtual Rectangle GetAvailableScreenSize(int i = -1) = 0; virtual int GetClosestScreenNumber(const Rectangle&) = 0; /** * @brief Gets the number of available screens in a multi-screen environment. * * @return the number of available screens in a multi-screen environment. */ virtual unsigned int GetScreenNumber() = 0; /** * @brief Gets the number of the primary screen. * * @return the number of the primary screen. */ virtual int GetPrimaryScreenNumber() = 0; /** * Converts the given rectangle from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert rectangle to convert * @return a rectangle in control coordinates * @since 3.0 */ virtual Rectangle ToControl(void* coordinateSystem, const Rectangle& toConvert) = 0; /** * Converts the given point from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert point to convert * @return a point in control coordinates * @since 3.0 */ virtual Point ToControl(void* coordinateSystem, const Point& toConvert) = 0; /** * Converts the given rectangle from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert rectangle to convert * @return a rectangle in display coordinates * @since 3.0 */ virtual Rectangle ToDisplay(void* coordinateSystem, const Rectangle& toConvert) = 0; /** * Converts the given point from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert point to convert * @return a point in display coordinates * @since 3.0 */ virtual Point ToDisplay(void* coordinateSystem, const Point& toConvert) = 0; }; } Q_DECLARE_INTERFACE(berry::GuiWidgetsTweaklet, "org.blueberry.GuiWidgetsTweaklet") #endif /* BERRYGUIWIDGETSTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h index 3aea7758db..0f87d631ce 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h @@ -1,52 +1,49 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYIMAGETWEAKLET_H_ #define BERRYIMAGETWEAKLET_H_ #include #include "../internal/berryTweaklets.h" #include "../berryImageDescriptor.h" #include namespace berry { /** * Provides the set of cursors used for drag-and-drop. */ -struct BERRY_UI ImageTweaklet : public Object +struct BERRY_UI ImageTweaklet { - - berryInterfaceMacro(ImageTweaklet, berry); - static Tweaklets::TweakKey KEY; virtual SmartPointer CreateFromFile(const std::string& filename, const std::string& pluginid) = 0; virtual SmartPointer CreateFromImage(void* img) = 0; virtual SmartPointer GetMissingImageDescriptor() = 0; virtual void DestroyImage(const void* img) = 0; }; } -Q_DECLARE_INTERFACE(berry::ImageTweaklet, "orb.blueberry.ImageTweaklet") +Q_DECLARE_INTERFACE(berry::ImageTweaklet, "org.blueberry.ImageTweaklet") #endif /* BERRYIMAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h index b221e72a2f..4f153f068e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h @@ -1,160 +1,158 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYMESSAGEDIALOGTWEAKLET_H_ #define BERRYMESSAGEDIALOGTWEAKLET_H_ #include #include "../berryShell.h" #include "../dialogs/berryIDialog.h" #include "../internal/berryTweaklets.h" #include #include #include namespace berry { /** * A dialog for showing messages to the user. */ -struct BERRY_UI MessageDialogTweaklet : public Object +struct BERRY_UI MessageDialogTweaklet { - berryInterfaceMacro(MessageDialogTweaklet, berry); - static Tweaklets::TweakKey KEY; /** * Convenience method to open a simple confirm (OK/Cancel) dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ virtual bool OpenConfirm(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard error dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenError(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard information dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenInformation(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a simple Yes/No question dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ virtual bool OpenQuestion(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard warning dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenWarning(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Create a message dialog. Note that the dialog will have no visual * representation (no widgets) until it is told to open. *

* The labels of the buttons to appear in the button bar are supplied in * this constructor as an array. The open method will return * the index of the label in this array corresponding to the button that was * pressed to close the dialog. If the dialog was dismissed without pressing * a button (ESC, etc.) then -1 is returned. Note that the open * method blocks. *

* * @param parentShell * the parent shell * @param dialogTitle * the dialog title, or null if none * @param dialogTitleImage * the dialog title image, or null if none * @param dialogMessage * the dialog message * @param dialogImageType * one of the following values: *
    *
  • IDialog::NONE for a dialog with no * image
  • *
  • IDialog::ERR for a dialog with an * error image
  • *
  • IDialog::INFORMATION for a dialog * with an information image
  • *
  • IDialog::QUESTION for a dialog with a * question image
  • *
  • IDialog::WARNING for a dialog with a * warning image
  • *
* @param dialogButtonLabels * an array of labels for the buttons in the button bar * @param defaultIndex * the index in the button label array of the default button */ virtual IDialog::Pointer MessageDialog(Shell::Pointer parentShell, const std::string& dialogTitle, void* dialogTitleImage, const std::string& dialogMessage, int dialogImageType, const std::vector& dialogButtonLabels, int defaultIndex) = 0; }; } Q_DECLARE_INTERFACE(berry::MessageDialogTweaklet, "org.blueberry.MessageDialogTweaklet") #endif /* BERRYMESSAGEDIALOGTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h index 6e87a48e1d..9cf9f808ef 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h @@ -1,46 +1,45 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYWORKBENCHPAGETWEAKLET_H_ #define BERRYWORKBENCHPAGETWEAKLET_H_ #include "../internal/berryTweaklets.h" #include "../berryIWorkbenchPage.h" namespace berry { -struct BERRY_UI WorkbenchPageTweaklet : public Object +struct BERRY_UI WorkbenchPageTweaklet { - berryInterfaceMacro(WorkbenchPageTweaklet, berry); static Tweaklets::TweakKey KEY; virtual void* CreateClientComposite(void* pageControl) = 0; virtual void* CreatePaneControl(void* parent) = 0; virtual Object::Pointer CreateStatusPart(void* parent, const std::string& title, const std::string& msg) = 0; virtual IEditorPart::Pointer CreateErrorEditorPart(const std::string& partName, const std::string& msg) = 0; }; } Q_DECLARE_INTERFACE(berry::WorkbenchPageTweaklet, "org.blueberry.WorkbenchPageTweaklet") #endif /* BERRYWORKBENCHPAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h index 5c7ca2b975..26bdfb63ae 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h @@ -1,55 +1,54 @@ /*========================================================================= 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. =========================================================================*/ #ifndef BERRYWORKBENCHTWEAKLET_H_ #define BERRYWORKBENCHTWEAKLET_H_ #include "../internal/berryTweaklets.h" #include "../berryShell.h" #include "../berryDisplay.h" #include "../dialogs/berryIDialog.h" namespace berry { class WorkbenchWindow; -struct BERRY_UI WorkbenchTweaklet : public Object +struct BERRY_UI WorkbenchTweaklet { - berryInterfaceMacro(WorkbenchTweaklet, berry); static Tweaklets::TweakKey KEY; static const std::string DIALOG_ID_SHOW_VIEW; // = "org.blueberry.ui.dialogs.showview"; virtual Display* CreateDisplay() = 0; virtual bool IsRunning() = 0; virtual SmartPointer CreateWorkbenchWindow(int number) = 0; virtual IDialog::Pointer CreateStandardDialog(const std::string& id) = 0; }; } Q_DECLARE_INTERFACE(berry::WorkbenchTweaklet, "org.blueberry.WorkbenchTweaklet") #endif /* BERRYWORKBENCHTWEAKLET_H_ */ diff --git a/CMakeExternals/CTK.cmake b/CMakeExternals/CTK.cmake index 922d0aaf43..c8addf3ee3 100644 --- a/CMakeExternals/CTK.cmake +++ b/CMakeExternals/CTK.cmake @@ -1,37 +1,38 @@ #----------------------------------------------------------------------------- # CTK #----------------------------------------------------------------------------- IF(MITK_USE_CTK) # Sanity checks IF(DEFINED CTK_DIR AND NOT EXISTS ${CTK_DIR}) MESSAGE(FATAL_ERROR "CTK_DIR variable is defined but corresponds to non-existing directory") ENDIF() SET(proj CTK) SET(proj_DEPENDENCIES ) SET(CTK_DEPENDS ${proj}) IF(NOT DEFINED CTK_DIR) ExternalProject_Add(${proj} GIT_REPOSITORY git://github.com/commontk/CTK.git + GIT_TAG origin/master BINARY_DIR ${proj}-build INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} -DDESIRED_QT_VERSION:STRING=4 -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DCTK_LIB_DICOM/Widgets:BOOL=ON DEPENDS ${proj_DEPENDENCIES} ) SET(CTK_DIR ${CMAKE_CURRENT_BINARY_DIR}/${proj}-build) ELSE() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") ENDIF() ENDIF()