diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp index f59a422aa6..e05e69c7bb 100644 --- a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp +++ b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp @@ -1,497 +1,498 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryInternalPlatform.h" #include "berryLog.h" #include "berryLogImpl.h" #include "berryPlatform.h" #include "berryPlatformException.h" #include "berryDebugUtil.h" #include "berryPlatformException.h" #include "berryCTKPluginActivator.h" #include "berryPlatformException.h" #include "berryApplicationContainer.h" #include "berryProduct.h" #include "berryIBranding.h" //#include "event/berryPlatformEvents.h" //#include "berryPlatformLogChannel.h" #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include US_INITIALIZE_MODULE namespace berry { QMutex InternalPlatform::m_Mutex; bool InternalPlatform::DEBUG = false; bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false; InternalPlatform::InternalPlatform() : m_Initialized(false) , m_ConsoleLog(false) , m_Context(nullptr) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { QMutexLocker lock(&m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const { ctkDebugOptions* options = GetDebugOptions(); if (options != nullptr) { return options->getOption(option, defaultValue); } return QVariant(); } IAdapterManager* InternalPlatform::GetAdapterManager() const { AssertInitialized(); return nullptr; } SmartPointer InternalPlatform::GetProduct() const { if (product.IsNotNull()) return product; ApplicationContainer* container = org_blueberry_core_runtime_Activator::GetContainer(); IBranding* branding = container == nullptr ? nullptr : container->GetBranding(); if (branding == nullptr) return IProduct::Pointer(); IProduct::Pointer brandingProduct = branding->GetProduct(); if (!brandingProduct) { brandingProduct = new Product(branding); } product = brandingProduct; return product; } void InternalPlatform::InitializePluginPaths() { QMutexLocker lock(&m_Mutex); // Add search paths for Qt plugins for(const auto& qtPluginPath : m_Context->getProperty(Platform::PROP_QTPLUGIN_PATH).toStringList()) { if (qtPluginPath.isEmpty()) continue; if (QFile::exists(qtPluginPath)) { QCoreApplication::addLibraryPath(qtPluginPath); } else if (m_ConsoleLog) { BERRY_WARN << "Qt plugin path does not exist: " << qtPluginPath.toStdString(); } } // Add a default search path. It is assumed that installed applications // provide their Qt plugins in that path. static const QString defaultQtPluginPath = QCoreApplication::applicationDirPath() + "/plugins"; if (QFile::exists(defaultQtPluginPath)) { QCoreApplication::addLibraryPath(defaultQtPluginPath); } if (m_ConsoleLog) { std::string pathList; foreach(QString libPath, QCoreApplication::libraryPaths()) { pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString(); } BERRY_INFO << "Qt library search paths: " << pathList; } /* m_ConfigPath.setPath(m_Context->getProperty("application.configDir").toString()); m_InstancePath.setPath(m_Context->getProperty("application.dir").toString()); QString installPath = m_Context->getProperty(Platform::PROP_HOME).toString(); if (installPath.isEmpty()) { m_InstallPath = m_InstancePath; } else { m_InstallPath.setPath(installPath); } QString dataLocation = m_Context->getProperty(Platform::PROP_STORAGE_DIR).toString(); if (!storageDir.isEmpty()) { if (dataLocation.at(dataLocation.size()-1) != '/') { dataLocation += '/'; } m_UserPath.setPath(dataLocation); } else { // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + this->getOrganizationName() + "/" + this->getApplicationName() + '_'; dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; m_UserPath.setPath(dataLocation); } BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath(); QFileInfo userFile(m_UserPath.absolutePath()); if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable()) { QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName())); BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath; QDir().mkpath(tmpPath); userFile.setFile(tmpPath); } m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins"); QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log")); m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString()); */ } ctkDebugOptions* InternalPlatform::GetDebugOptions() const { return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService(); } IApplicationContext* InternalPlatform::GetApplicationContext() const { QList refs; try { refs = m_Context->getServiceReferences("(blueberry.application.type=main.thread)"); } catch (const std::invalid_argument&) { return nullptr; } if (refs.isEmpty()) return nullptr; // assumes the application context is available as a service IApplicationContext* result = m_Context->getService(refs.front()); if (result != nullptr) { m_Context->ungetService(refs.front()); return result; } return nullptr; } void InternalPlatform::Start(ctkPluginContext* context) { this->m_Context = context; m_ConsoleLog = m_Context->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool(); OpenServiceTrackers(); this->InitializePluginPaths(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(m_UserPath); #endif InitializeDebugFlags(); this->m_Initialized = true; } void InternalPlatform::Stop(ctkPluginContext* /*context*/) { AssertInitialized(); this->m_Initialized = false; CloseServiceTrackers(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::SaveState(m_UserPath); #endif this->m_Context = nullptr; } void InternalPlatform::AssertInitialized() const { if (!m_Initialized) { throw PlatformException("The Platform has not been initialized yet!"); } } void InternalPlatform::OpenServiceTrackers() { ctkPluginContext* context = this->m_Context; instanceLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::INSTANCE_FILTER))); instanceLocation->open(); userLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::USER_FILTER))); userLocation->open(); configurationLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::CONFIGURATION_FILTER))); configurationLocation->open(); installLocation.reset(new ctkServiceTracker(context, ctkLDAPSearchFilter(ctkLocation::INSTALL_FILTER))); installLocation->open(); m_RegistryTracker.reset(new ctkServiceTracker(context)); m_RegistryTracker->open(); m_DebugTracker.reset(new ctkServiceTracker(context)); m_DebugTracker->open(); } void InternalPlatform::CloseServiceTrackers() { if (!m_RegistryTracker.isNull()) { m_RegistryTracker->close(); m_RegistryTracker.reset(); } if (!m_DebugTracker.isNull()) { m_DebugTracker->close(); m_DebugTracker.reset(); } if (!configurationLocation.isNull()) { configurationLocation->close(); configurationLocation.reset(); } if (!installLocation.isNull()) { installLocation->close(); installLocation.reset(); } if (!instanceLocation.isNull()) { instanceLocation->close(); instanceLocation.reset(); } if (!userLocation.isNull()) { userLocation->close(); userLocation.reset(); } } void InternalPlatform::InitializeDebugFlags() { DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool(); if (DEBUG) { DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool(); } } IExtensionRegistry* InternalPlatform::GetExtensionRegistry() { return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService(); } mitk::IPreferencesService *InternalPlatform::GetPreferencesService() { return mitk::CoreServices::GetPreferencesService(); } ctkLocation* InternalPlatform::GetConfigurationLocation() { this->AssertInitialized(); return configurationLocation->getService(); } ctkLocation* InternalPlatform::GetInstallLocation() { this->AssertInitialized(); return installLocation->getService(); } ctkLocation* InternalPlatform::GetInstanceLocation() { this->AssertInitialized(); return instanceLocation->getService(); } QDir InternalPlatform::GetStateLocation(const QSharedPointer& plugin) { ctkLocation* service = GetInstanceLocation(); if (service == nullptr) { throw ctkIllegalStateException("No instance data can be specified."); } QUrl url = GetInstanceLocation()->getDataArea(plugin->getSymbolicName()); if (!url.isValid()) { throw ctkIllegalStateException("The instance data location has not been specified yet."); } QDir location(url.toLocalFile()); if (!location.exists()) { if (!location.mkpath(location.absolutePath())) { throw PlatformException(QString("Could not create plugin state location \"%1\"").arg(location.absolutePath())); } } return location; } //PlatformEvents& InternalPlatform::GetEvents() //{ // return m_Events; //} ctkLocation* InternalPlatform::GetUserLocation() { this->AssertInitialized(); return userLocation->getService(); } ILog *InternalPlatform::GetLog(const QSharedPointer &plugin) const { LogImpl* result = m_Logs.value(plugin->getPluginId()); if (result != nullptr) return result; // ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService(); // Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME); // result = new Log(bundle, logger); // ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService(); // logReader.addLogListener(result, result); // logs.put(bundle, result); // return result; result = new LogImpl(plugin); m_Logs.insert(plugin->getPluginId(), result); return result; } bool InternalPlatform::IsRunning() const { QMutexLocker lock(&m_Mutex); try { return m_Initialized && m_Context && m_Context->getPlugin()->getState() == ctkPlugin::ACTIVE; } catch (const ctkIllegalStateException&) { return false; } } QSharedPointer InternalPlatform::GetPlugin(const QString &symbolicName) { QList > plugins = m_Context->getPlugins(); QSharedPointer res(nullptr); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (res.isNull()) { res = plugin; } else if (res->getVersion().compare(plugin->getVersion()) < 0) { res = plugin; } } } return res; } QList > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version) { QList > plugins = m_Context->getPlugins(); QMap > selected; ctkVersion versionObj(version); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (plugin->getVersion().compare(versionObj) > -1) { selected.insert(plugin->getVersion(), plugin); } } } QList > sortedPlugins = selected.values(); QList > reversePlugins; - qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end()); + std::copy_backward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end()); return reversePlugins; } QStringList InternalPlatform::GetApplicationArgs() const { QStringList result; IApplicationContext* appContext = this->GetApplicationContext(); if (appContext) { QHash args = appContext->GetArguments(); result = args[IApplicationContext::APPLICATION_ARGS].toStringList(); } return result; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp index b2e87cfab6..99cfd91157 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp @@ -1,251 +1,251 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryChangeToPerspectiveMenu.h" #include #include #include #include #include #include #include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryPreferenceConstants.h" #include #include namespace berry { const QString ChangeToPerspectiveMenu::NO_TARGETS_MSG = ""; bool PerspectiveComparator(const IPerspectiveDescriptor::Pointer& d1, const IPerspectiveDescriptor::Pointer& d2) { return d1->GetLabel() < d2->GetLabel(); } ChangeToPerspectiveMenu::ChangeToPerspectiveMenu(IWorkbenchWindow* window, const QString& id) : ContributionItem(id) , window(window) , reg(window->GetWorkbench()->GetPerspectiveRegistry()) , showActive(true) , dirty(true) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( window, QString::null, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // indicate that a open perspectives submenu has been created /* if (WorkbenchWindow* window = dynamic_cast(window)) { window->AddSubmenu(WorkbenchWindow::OPEN_PERSPECTIVE_SUBMENU); } */ } void ChangeToPerspectiveMenu::Fill(QMenu* menu, QAction* before) { if (MenuManager* mm = dynamic_cast(GetParent())) { this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); } if (!dirty) { return; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); if (items.isEmpty()) { auto action = new QAction(NO_TARGETS_MSG, menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { item->Fill(menu, before); } } dirty = false; } bool ChangeToPerspectiveMenu::IsDirty() const { return dirty; } bool ChangeToPerspectiveMenu::IsDynamic() const { return true; } void ChangeToPerspectiveMenu::AboutToShow(IMenuManager* manager) { manager->MarkDirty(); dirty = true; } void ChangeToPerspectiveMenu::FillMenu(IMenuManager* manager) { // Clear out the manager so that we have a blank slate. manager->RemoveAll(); // Collect and sort perspective descriptors. QList persps = GetPerspectiveShortcuts(); - qSort(persps.begin(), persps.end(), PerspectiveComparator); + std::sort(persps.begin(), persps.end(), PerspectiveComparator); /* * Convert the perspective descriptors to command parameters, and filter * using the activity/capability mechanism. */ for (const IPerspectiveDescriptor::Pointer &descriptor : qAsConst(persps)) { CommandContributionItemParameter::Pointer ccip = GetItem(descriptor); // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); manager->Add(item); } auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); bool showOther = prefs->GetBool(WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU, true); if (showOther) { // Add a separator and then "Other..." if (!manager->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); manager->Add(separator); } manager->Add(showDlgItem); } } SmartPointer ChangeToPerspectiveMenu::GetItem(const IPerspectiveDescriptor::Pointer& desc) const { auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); int mode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = window->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page.IsNotNull()) { persp = page->GetPerspective(); } QString perspId = desc->GetId(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: typedef PluginCCIP Self; static const char* GetStaticClassName() { return "PluginCCIP"; } berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution) PluginCCIP(const IPerspectiveDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { PerspectiveDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const override { return localId; } QString GetPluginId() const override { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, perspId, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, CommandContributionItem::STYLE_PUSH)); parms->label = desc->GetLabel(); parms->icon = desc->GetImageDescriptor(); Object::Pointer strId(new ObjectString(perspId)); parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID, strId); // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp.IsNotNull()) { Object::Pointer bNewWnd(new ObjectBool(true)); parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW, bNewWnd); } return parms; } QList > ChangeToPerspectiveMenu::GetPerspectiveShortcuts() const { QList list; IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return list; } QList ids = page->GetPerspectiveShortcuts(); for (int i = 0; i < ids.size(); i++) { IPerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId(ids[i]); if (desc.IsNotNull() && !list.contains(desc)) { /* if (WorkbenchActivityHelper::FilterItem(desc)) { continue; } */ list.push_back(desc); } } return list; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp index 920abd7639..139d7056f3 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp @@ -1,1295 +1,1295 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryEditorRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryEditorRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { const QString EditorRegistry::EMPTY_EDITOR_ID = "org.blueberry.ui.internal.emptyEditorTab"; QHash EditorRegistry::EditorMap::defaultMap; QHash EditorRegistry::EditorMap::map; EditorRegistry::RelatedRegistry::RelatedRegistry(EditorRegistry* reg) : editorRegistry(reg) { } QList EditorRegistry::RelatedRegistry::GetRelatedObjects( const QString& fileName) { IFileEditorMapping::Pointer mapping = editorRegistry->GetMappingFor(fileName); if (mapping.IsNull()) { return QList(); } return mapping->GetEditors(); } EditorRegistry::EditorRegistry() : relatedRegistry(this) { this->InitialIdToEditorMap(mapIDtoEditor); this->InitializeFromStorage(); //IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker(); //tracker.registerHandler(this, // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); } void EditorRegistry::AddEditorFromPlugin(EditorDescriptor::Pointer editor, const QList& extensions, const QList& filenames, const QList& /*contentTypeVector*/, bool bDefault) { //PlatformUI.getWorkbench().getExtensionTracker().registerObject(editor.getConfigurationElement().getDeclaringExtension(), editor, IExtensionTracker.REF_WEAK); // record it in our quick reference list sortedEditorsFromPlugins.push_back(editor); // add it to the table of mappings for (QList::const_iterator itr = extensions.begin(); itr != extensions.end(); ++itr) { QString fileExtension = *itr; if (!fileExtension.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor("*." + fileExtension); if (mapping.IsNull()) { // no mapping for that extension mapping = new FileEditorMapping(fileExtension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // add it to the table of mappings for (QList::const_iterator itr = filenames.begin(); itr != filenames.end(); ++itr) { QString filename = *itr; if (!filename.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(filename); if (mapping.IsNull()) { // no mapping for that extension QString name; QString extension; int index = filename.indexOf('.'); if (index == -1) { name = filename; extension = ""; } else { name = filename.left(index); extension = filename.mid(index + 1); } mapping = new FileEditorMapping(name, extension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // for (QList::const_iterator itr = contentTypeVector.begin(); // itr != contentTypeVector.end(); ++itr) // { // QString contentTypeId = *itr; // if (!contentTypeId.empty()) // { // IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeId); // if (contentType != null) // { // IEditorDescriptor [] editorArray = (IEditorDescriptor[]) contentTypeToEditorMappings.get(contentType); // if (editorArray == null) // { // editorArray = new IEditorDescriptor[] // { editor}; // contentTypeToEditorMappings.put(contentType, editorArray); // } // else // { // IEditorDescriptor [] newArray = new IEditorDescriptor[editorArray.length + 1]; // if (bDefault) // { // default editors go to the front of the line // newArray[0] = editor; // System.arraycopy(editorArray, 0, newArray, 1, editorArray.length); // } // else // { // newArray[editorArray.length] = editor; // System.arraycopy(editorArray, 0, newArray, 0, editorArray.length); // } // contentTypeToEditorMappings.put(contentType, newArray); // } // } // } // } // Update editor map. mapIDtoEditor[editor->GetId()] = editor; } void EditorRegistry::AddExternalEditorsToEditorMap() { // Add registered editors (may include external editors). QList maps = typeEditorMappings.AllMappings(); for (int i = 0; i < maps.size(); ++i) { FileEditorMapping::Pointer map = maps[i]; QList descArray = map->GetEditors(); for (QList::iterator itr = descArray.begin(); itr != descArray.end(); ++itr) { mapIDtoEditor[(*itr)->GetId()] = itr->Cast (); } } } IEditorDescriptor::Pointer EditorRegistry::FindEditor(const QString& id) { return mapIDtoEditor[id]; } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor() { // the default editor will always be the system external editor // this should never return null return this->FindEditor(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor( const QString& fileName) { //return this->GetDefaultEditor(filename, guessAtContentType(filename)); return this->GetEditorForContentType(fileName /*, contentType*/); } IEditorDescriptor::Pointer EditorRegistry::GetEditorForContentType( const QString& filename /*IContentType contentType*/) { IEditorDescriptor::Pointer desc; ; QList contentTypeResults = this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); if (contentTypeResults.size() > 0) { desc = contentTypeResults.front(); } return desc; } QList EditorRegistry::FindRelatedObjects( /*IContentType type,*/const QString& fileName, RelatedRegistry& /*registry*/) { QList allRelated; QList nonDefaultFileEditors; QList related; if (!fileName.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(fileName); if (!mapping.IsNull()) { // backwards compatibility - add editors flagged as "default" related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } // add all filename editors to the nonDefaultList // we'll later try to add them all after content types are resolved // duplicates (ie: default editors) will be ignored QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } int index = fileName.indexOf('.'); if (index != -1) { QString extension = "*" + fileName.mid(index); mapping = this->GetMappingFor(extension); if (!mapping.IsNull()) { related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } } } // if (type != null) { // // now add any objects directly related to the content type // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // // } // if (type != null) { // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // } // } // add all non-default editors to the list for (QList::iterator i = nonDefaultFileEditors.begin(); i != nonDefaultFileEditors.end(); ++i) { IEditorDescriptor::Pointer editor = *i; if (std::find(allRelated.begin(), allRelated.end(), editor) == allRelated.end()) { allRelated.push_back(editor); } } return allRelated; } QList EditorRegistry::GetEditors( const QString& filename) { //return getEditors(filename, guessAtContentType(filename)); return this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); } QList EditorRegistry::GetFileEditorMappings() { QList array(typeEditorMappings.AllMappings()); std::sort(array.begin(), array.end(), CmpFileEditorMapping()); QList result; for (QList::iterator itr = array.begin(); itr != array.end(); ++itr) { result.push_back(itr->Cast ()); } return result; } FileEditorMapping::Pointer EditorRegistry::GetMappingFor(const QString& ext) { QString key = this->MappingKeyFor(ext); return typeEditorMappings.Get(key); } QList EditorRegistry::GetMappingForFilename( const QString& filename) { QList mapping; // Lookup on entire filename mapping[0] = this->GetMappingFor(filename); // Lookup on filename's extension int index = filename.indexOf('.'); if (index != -1) { QString extension = filename.mid(index); mapping[1] = this->GetMappingFor("*" + extension); } return mapping; } // QList EditorRegistry::GetSortedEditorsFromOS() // { // List externalEditors = new ArrayList(); // Program[] programs = Program.getPrograms(); // // for (int i = 0; i < programs.length; i++) // { // //1FPLRL2: ITPUI:WINNT - NOTEPAD editor cannot be launched // //Some entries start with %SystemRoot% // //For such cases just use the file name as they are generally // //in directories which are on the path // /* // * if (fileName.charAt(0) == '%') { fileName = name + ".exe"; } // */ // // EditorDescriptor editor = new EditorDescriptor(); // editor.setOpenMode(EditorDescriptor.OPEN_EXTERNAL); // editor.setProgram(programs[i]); // // // determine the program icon this editor would need (do not let it // // be cached in the workbench registry) // ImageDescriptor desc = new ExternalProgramImageDescriptor( // programs[i]); // editor.setImageDescriptor(desc); // externalEditors.add(editor); // } // // Object[] tempArray = sortEditors(externalEditors); // IEditorDescriptor[] array = new IEditorDescriptor[externalEditors // .size()]; // for (int i = 0; i < tempArray.length; i++) // { // array[i] = (IEditorDescriptor) tempArray[i]; // } // return array; // } QList EditorRegistry::GetSortedEditorsFromPlugins() { QList result; for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { result.push_back((*itr).Cast ()); } return result; } void EditorRegistry::InitialIdToEditorMap( QHash& map) { this->AddSystemEditors(map); } void EditorRegistry::AddSystemEditors( QHash& map) { // there will always be a system external editor descriptor EditorDescriptor::Pointer editor(new EditorDescriptor()); editor->SetID(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); editor->SetName("System Editor"); editor->SetOpenMode(EditorDescriptor::OPEN_EXTERNAL); // @issue we need a real icon for this editor? map[IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID] = editor; // there may be a system in-place editor if supported by platform // if (ComponentSupport.inPlaceEditorSupported()) // { // editor = new EditorDescriptor(); // editor.setID(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); // editor.setName(WorkbenchMessages.SystemInPlaceDescription_name); // editor.setOpenMode(EditorDescriptor.OPEN_INPLACE); // // @issue we need a real icon for this editor? // map.put(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, editor); // } EditorDescriptor::Pointer emptyEditorDescriptor(new EditorDescriptor()); emptyEditorDescriptor->SetID(EMPTY_EDITOR_ID); emptyEditorDescriptor->SetName("(Empty)"); //$NON-NLS-1$ //emptyEditorDescriptor.setImageDescriptor(WorkbenchImages //.getImageDescriptor(IWorkbenchGraphicConstants.IMG_OBJ_ELEMENT)); map[EMPTY_EDITOR_ID] = emptyEditorDescriptor; } void EditorRegistry::InitializeFromStorage() { //Get editors from the registry EditorRegistryReader registryReader; registryReader.AddEditors(this); this->SortInternalEditors(); this->RebuildInternalEditorMap(); // IPreferenceStore store = PlatformUI.getPreferenceStore(); // String defaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS); // String chachedDefaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS_CACHE); //If defaults has changed load it afterwards so it overrides the users // associations. //if (defaultEditors == null // || defaultEditors.equals(chachedDefaultEditors)) //{ this->SetProductDefaults("");//defaultEditors); this->LoadAssociations(); //get saved earlier state // } // else // { // loadAssociations(); //get saved earlier state // setProductDefaults(defaultEditors); // store.putValue(IPreferenceConstants.DEFAULT_EDITORS_CACHE, // defaultEditors); // } this->AddExternalEditorsToEditorMap(); } void EditorRegistry::SetProductDefaults(const QString& defaultEditors) { if (defaultEditors.isEmpty()) { return; } // Poco::StringTokenizer extEditors(defaultEditors, // IPreferenceConstants::SEPARATOR, Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); // while (extEditors.hasMoreTokens()) // { // String extEditor = extEditors.nextToken().trim(); // int index = extEditor.indexOf(':'); // if (extEditor.length() < 3 || index <= 0 || index // >= (extEditor.length() - 1)) // { // //Extension and id must have at least one char. // WorkbenchPlugin // .log("Error setting default editor. Could not parse '" + extEditor // + "'. Default editors should be specified as '*.ext1:editorId1;*.ext2:editorId2'"); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } // String ext = extEditor.substring(0, index).trim(); // String editorId = extEditor.substring(index + 1).trim(); // FileEditorMapping mapping = getMappingFor(ext); // if (mapping == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find mapping for '" // + ext + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // EditorDescriptor editor = (EditorDescriptor) findEditor(editorId); // if (editor == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find editor: '" // + editorId + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // mapping.setDefaultEditor(editor); // } } bool EditorRegistry::ReadEditors( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the editors defined in the preferences store // String xmlString = store.getString(IPreferenceConstants.EDITORS); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.EDITOR_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // XMLMemento memento = XMLMemento.createReadRoot(reader); // EditorDescriptor editor; // IMemento[] edMementos = memento // .getChildren(IWorkbenchConstants.TAG_DESCRIPTOR); // // Get the editors and validate each one // for (int i = 0; i < edMementos.length; i++) // { // editor = new EditorDescriptor(); // boolean valid = editor.loadValues(edMementos[i]); // if (!valid) // { // continue; // } // if (editor.getPluginID() != null) // { // //If the editor is from a plugin we use its ID to look it // // up in the mapping of editors we // //have obtained from plugins. This allows us to verify that // // the editor is still valid // //and allows us to get the editor description from the // // mapping table which has // //a valid config element field. // EditorDescriptor validEditorDescritor = (EditorDescriptor) mapIDtoEditor // .get(editor.getId()); // if (validEditorDescritor != null) // { // editorTable.put(validEditorDescritor.getId(), // validEditorDescritor); // } // } // else // { //This is either from a program or a user defined // // editor // ImageDescriptor descriptor; // if (editor.getProgram() == null) // { // descriptor = new ProgramImageDescriptor(editor // .getFileName(), 0); // } // else // { // descriptor = new ExternalProgramImageDescriptor(editor // .getProgram()); // } // editor.setImageDescriptor(descriptor); // editorTable.put(editor.getId(), editor); // } // } // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // e.printStackTrace(); // } // //Ignore this as the workbench may not yet have saved any state // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } void EditorRegistry::ReadResources( QHash& /*editorTable*/, std::ostream& /*reader*/) { // XMLMemento memento = XMLMemento.createReadRoot(reader); // String versionString = memento.getString(IWorkbenchConstants.TAG_VERSION); // boolean versionIs31 = "3.1".equals(versionString); //$NON-NLS-1$ // // IMemento[] extMementos = memento // .getChildren(IWorkbenchConstants.TAG_INFO); // for (int i = 0; i < extMementos.length; i++) // { // String name = extMementos[i] // .getString(IWorkbenchConstants.TAG_NAME); // if (name == null) // { // name = "*"; //$NON-NLS-1$ // } // String extension = extMementos[i] // .getString(IWorkbenchConstants.TAG_EXTENSION); // IMemento[] idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_EDITOR); // String[] editorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // editorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DELETED_EDITOR); // String[] deletedEditorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // deletedEditorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // FileEditorMapping mapping = getMappingFor(name + "." + extension); //$NON-NLS-1$ // if (mapping == null) // { // mapping = new FileEditorMapping(name, extension); // } // List editors = new ArrayList(); // for (int j = 0; j < editorIDs.length; j++) // { // if (editorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(editorIDs[j]); // if (editor != null) // { // editors.add(editor); // } // } // } // List deletedEditors = new ArrayList(); // for (int j = 0; j < deletedEditorIDs.length; j++) // { // if (deletedEditorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(deletedEditorIDs[j]); // if (editor != null) // { // deletedEditors.add(editor); // } // } // } // // List defaultEditors = new ArrayList(); // // if (versionIs31) // { // parse the new format // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // String[] defaultEditorIds = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // defaultEditorIds[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // for (int j = 0; j < defaultEditorIds.length; j++) // { // if (defaultEditorIds[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(defaultEditorIds[j]); // if (editor != null) // { // defaultEditors.add(editor); // } // } // } // } // else // { // guess at pre 3.1 format defaults // if (!editors.isEmpty()) // { // EditorDescriptor editor = (EditorDescriptor) editors.get(0); // if (editor != null) // { // defaultEditors.add(editor); // } // } // defaultEditors.addAll(Arrays.asList(mapping.getDeclaredDefaultEditors())); // } // // // Add any new editors that have already been read from the registry // // which were not deleted. // IEditorDescriptor[] editorsArray = mapping.getEditors(); // for (int j = 0; j < editorsArray.length; j++) // { // if (!contains(editors, editorsArray[j]) // && !deletedEditors.contains(editorsArray[j])) // { // editors.add(editorsArray[j]); // } // } // // Map the editor(s) to the file type // mapping.setEditorsList(editors); // mapping.setDeletedEditorsList(deletedEditors); // mapping.setDefaultEditors(defaultEditors); // typeEditorMappings.put(mappingKeyFor(mapping), mapping); // } } bool EditorRegistry::Contains( const QList& editorsArray, IEditorDescriptor::Pointer editorDescriptor) { IEditorDescriptor::Pointer currentEditorDescriptor; for (QList::const_iterator i = editorsArray.begin(); i != editorsArray.end(); ++i) { currentEditorDescriptor = *i; if (currentEditorDescriptor->GetId() == editorDescriptor->GetId()) { return true; } } return false; } bool EditorRegistry::ReadResources( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); // XXX: nobody cares about this return value if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the resource types // String xmlString = store.getString(IPreferenceConstants.RESOURCES); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.RESOURCE_TYPE_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // // Read the defined resources into the table // readResources(editorTable, reader); // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage); // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } bool EditorRegistry::LoadAssociations() { QHash editorTable; if (!this->ReadEditors(editorTable)) { return false; } return this->ReadResources(editorTable); } QString EditorRegistry::MappingKeyFor(const QString& type) { // keep everything lower case for case-sensitive platforms return type.toLower(); } QString EditorRegistry::MappingKeyFor(FileEditorMapping::Pointer mapping) { return this->MappingKeyFor(mapping->GetName() + (mapping->GetExtension().size() == 0 ? "" : "." + mapping->GetExtension())); //$NON-NLS-1$ //$NON-NLS-2$ } void EditorRegistry::RebuildEditorMap() { this->RebuildInternalEditorMap(); this->AddExternalEditorsToEditorMap(); } void EditorRegistry::RebuildInternalEditorMap() { EditorDescriptor::Pointer desc; // Allocate a new map. mapIDtoEditor.clear(); this->InitialIdToEditorMap(mapIDtoEditor); // Add plugin editors. for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { desc = *itr; mapIDtoEditor[desc->GetId()] = desc; } } void EditorRegistry::SaveAssociations() { //Save the resource type descriptions // List editors = new ArrayList(); // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // // XMLMemento memento = XMLMemento // .createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // memento.putString(IWorkbenchConstants.TAG_VERSION, "3.1"); //$NON-NLS-1$ // FileEditorMapping maps[] = typeEditorMappings.userMappings(); // for (int mapsIndex = 0; mapsIndex < maps.length; mapsIndex++) // { // FileEditorMapping type = maps[mapsIndex]; // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_INFO); // editorMemento.putString(IWorkbenchConstants.TAG_NAME, type // .getName()); // editorMemento.putString(IWorkbenchConstants.TAG_EXTENSION, type // .getExtension()); // IEditorDescriptor[] editorArray = type.getEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeletedEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DELETED_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeclaredDefaultEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // } // Writer writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.RESOURCES, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, "Saving Problems", //$NON-NLS-1$ // "Unable to save resource associations."); //$NON-NLS-1$ // return; // } // // memento = XMLMemento.createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // Iterator itr = editors.iterator(); // while (itr.hasNext()) // { // EditorDescriptor editor = (EditorDescriptor) itr.next(); // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_DESCRIPTOR); // editor.saveValues(editorMemento); // } // writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.EDITORS, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, // "Error", "Unable to save resource associations."); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } } void EditorRegistry::SetFileEditorMappings( const QList& newResourceTypes) { typeEditorMappings.Clear(); for (int i = 0; i < newResourceTypes.size(); i++) { FileEditorMapping::Pointer mapping = newResourceTypes[i]; typeEditorMappings.Put(this->MappingKeyFor(mapping), mapping); } //extensionImages = new HashMap(); this->RebuildEditorMap(); //firePropertyChange(PROP_CONTENTS); } void EditorRegistry::SetDefaultEditor(const QString& fileName, const QString& editorId) { EditorDescriptor::Pointer desc = this->FindEditor(editorId).Cast< EditorDescriptor> (); QList mapping = this->GetMappingForFilename( fileName); if (!mapping[0].IsNull()) { mapping[0]->SetDefaultEditor(desc); } if (!mapping[1].IsNull()) { mapping[1]->SetDefaultEditor(desc); } } QList EditorRegistry::SortEditors( const QList& unsortedList) { QList result(unsortedList); std::sort(result.begin(), result.end(), CmpIEditorDescriptor()); return result; } void EditorRegistry::SortInternalEditors() { - qSort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor()); + std::sort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor()); } void EditorRegistry::EditorMap::PutDefault(const QString& key, FileEditorMapping::Pointer value) { defaultMap[key] = value; } void EditorRegistry::EditorMap::Put(const QString& key, FileEditorMapping::Pointer value) { QHash::iterator result = defaultMap.find(key); if (result != defaultMap.end()) { map[key] = value; } } FileEditorMapping::Pointer EditorRegistry::EditorMap::Get( const QString& key) { QHash::const_iterator result = map.find(key); if (result == map.end()) { return defaultMap[key]; } return result.value(); } void EditorRegistry::EditorMap::Clear() { defaultMap.clear(); map.clear(); } QList EditorRegistry::EditorMap::AllMappings() { QSet resultSet; QHash::const_iterator iter; for (iter = defaultMap.begin(); iter != defaultMap.end(); ++iter) { resultSet.insert(iter.value()); } for (iter = map.begin(); iter != map.end(); ++iter) { resultSet.insert(iter.value()); } return resultSet.values(); } QList EditorRegistry::EditorMap::UserMappings() { return map.values(); } bool EditorRegistry::IsSystemInPlaceEditorAvailable(const QString& /*filename*/) { //return ComponentSupport.inPlaceEditorAvailable(filename); return false; } bool EditorRegistry::IsSystemExternalEditorAvailable( const QString& /*filename*/) { // QString::size_type nDot = filename.find_last_of('.'); // if (nDot != QString::npos) // { // QString strName = filename.substr(nDot); // return Program.findProgram(strName) != null; // } return false; } void EditorRegistry::RemoveEditorFromMapping( QHash& map, IEditorDescriptor::Pointer desc) { FileEditorMapping::Pointer mapping; for (QHash::iterator iter = map.begin(); iter != map.end(); ++iter) { mapping = iter.value(); QList editors(mapping->GetEditors()); QList::iterator result = std::find( editors.begin(), editors.end(), desc); if (result != editors.end()) { mapping->RemoveEditor(result->Cast ()); editors.erase(result); } if (editors.empty()) { map.erase(iter); break; } } } IExtensionPoint::Pointer EditorRegistry::GetExtensionPointFilter() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_EDITOR); } QList EditorRegistry::GetUnifiedMappings() { QList standardMappings( dynamic_cast (PlatformUI::GetWorkbench() ->GetEditorRegistry())->GetFileEditorMappings()); QList allMappings(standardMappings); // mock-up content type extensions into IFileEditorMappings // IContentType [] contentTypes = Platform.getContentTypeManager().getAllContentTypes(); // for (int i = 0; i < contentTypes.length; i++) // { // IContentType type = contentTypes[i]; // String [] extensions = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC); // for (int j = 0; j < extensions.length; j++) // { // String extension = extensions[j]; // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if ("*".equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { //$NON-NLS-1$ // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, "*", extension); //$NON-NLS-1$ // allMappings.add(mockMapping); // } // } // // String [] filenames = type.getFileSpecs(IContentType.FILE_NAME_SPEC); // for (int j = 0; j < filenames.length; j++) // { // String wholename = filenames[j]; // int idx = wholename.indexOf('.'); // String name = idx == -1 ? wholename : wholename.substring(0, idx); // String extension = idx == -1 ? "" : wholename.substring(idx + 1); //$NON-NLS-1$ // // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if (name.equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, name, extension); // allMappings.add(mockMapping); // } // } // } return allMappings; } MockMapping::MockMapping(/*IContentType type,*/const QString& name, const QString& ext) : extension(ext), filename(name) { //this.contentType = type; } IEditorDescriptor::Pointer MockMapping::GetDefaultEditor() { // QList candidates = PlatformUI::GetWorkbench()->GetEditorRegistry() // ->GetEditorsForContentType(contentType); // if (candidates.empty()) // { // return IEditorDescriptor::Pointer(); // } // return candidates[0]; return IEditorDescriptor::Pointer(); } QList MockMapping::GetEditors() const { // QList editorsForContentType = (dynamic_cast(PlatformUI // ::GetWorkbench()->GetEditorRegistry()) // ->GetEditorsForContentType(contentType); // return editorsForContentType; return QList(); } QList MockMapping::GetDeletedEditors() const { return QList(); } QString MockMapping::GetExtension() const { return extension; } QString MockMapping::GetLabel() const { return filename + '.' + extension; } QString MockMapping::GetName() const { return filename; } bool MockMapping::operator==(const Object* obj) const { if (const MockMapping* other = dynamic_cast(obj)) { if (this == other) { return true; } //MockMapping mapping = (MockMapping) obj; if (!(this->filename == other->filename)) { return false; } if (!(this->extension == other->extension)) { return false; } if (!(this->GetEditors() == other->GetEditors())) { return false; } return this->GetDeletedEditors() == other->GetDeletedEditors(); } return false; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp index 281326281c..5b8cb25bb4 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp @@ -1,272 +1,272 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryQtStylePreferencePage.h" #include "berryWorkbenchPlugin.h" #include #include #include #include #include namespace { mitk::IPreferences* GetPreferences() { return berry::WorkbenchPlugin::GetDefault()->GetPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); } } namespace berry { QtStylePreferencePage::QtStylePreferencePage() { } void QtStylePreferencePage::Init(IWorkbench::Pointer ) { } void QtStylePreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference(); if (styleManagerRef) { styleManager = context->getService(styleManagerRef); } Update(); connect(controls.m_StylesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(StyleChanged(int))); connect(controls.m_FontComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_FontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(FontChanged(int))); connect(controls.m_PathList, SIGNAL(itemSelectionChanged()), this, SLOT(UpdatePathListButtons())); connect(controls.m_AddButton, SIGNAL(clicked(bool)), this, SLOT(AddPathClicked(bool))); connect(controls.m_EditButton, SIGNAL(clicked(bool)), this, SLOT(EditPathClicked(bool))); connect(controls.m_RemoveButton, SIGNAL(clicked(bool)), this, SLOT(RemovePathClicked(bool))); } void QtStylePreferencePage::FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle) { controls.m_StylesCombo->clear(); styles.clear(); styleManager->GetStyles(styles); - qSort(styles); + std::sort(styles.begin(), styles.end()); for (int i = 0; i < styles.size(); ++i) { controls.m_StylesCombo->addItem(styles.at(i).name, QVariant(styles.at(i).fileName)); } controls.m_StylesCombo->setCurrentIndex(styles.indexOf(currentStyle)); } void QtStylePreferencePage::FillFontCombo(const QString& currentFont) { controls.m_FontComboBox->clear(); QStringList fonts; styleManager->GetFonts(fonts); for (int i = 0; i < fonts.size(); ++i) { controls.m_FontComboBox->addItem(fonts.at(i)); } controls.m_FontComboBox->setCurrentIndex(fonts.indexOf(currentFont)); if (currentFont == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } } void QtStylePreferencePage::AddPath(const QString& path, bool updateCombo) { if (!controls.m_PathList->findItems(path, Qt::MatchCaseSensitive).isEmpty()) return; new QListWidgetItem(path, controls.m_PathList); styleManager->AddStyles(path); if (updateCombo) FillStyleCombo(oldStyle); } void QtStylePreferencePage::StyleChanged(int /*index*/) { QString fileName = controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString(); styleManager->SetStyle(fileName); } void QtStylePreferencePage::FontChanged(int /*index*/) { QString fontName = controls.m_FontComboBox->currentText(); int fontSize = controls.m_FontSizeSpinBox->value(); if (fontName == QString("<>")) { controls.m_FontSizeSpinBox->setEnabled(false); } else { controls.m_FontSizeSpinBox->setEnabled(true); } styleManager->SetFont(fontName); styleManager->SetFontSize(fontSize); styleManager->UpdateWorkbenchFont(); } void QtStylePreferencePage::AddPathClicked(bool /*checked*/) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir; if (item) initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) this->AddPath(dir, true); } void QtStylePreferencePage::RemovePathClicked(bool /*checked*/) { QList selection = controls.m_PathList->selectedItems(); QListIterator it(selection); while (it.hasNext()) { QListWidgetItem* item = it.next(); QString dir = item->text(); controls.m_PathList->takeItem(controls.m_PathList->row(item)); delete item; styleManager->RemoveStyles(dir); } if (!styleManager->Contains(oldStyle.fileName)) { oldStyle = styleManager->GetDefaultStyle(); } FillStyleCombo(oldStyle); } void QtStylePreferencePage::EditPathClicked(bool checked) { QListWidgetItem* item = controls.m_PathList->currentItem(); QString initialDir = item->text(); QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir); if (!dir.isEmpty()) { this->RemovePathClicked(checked); this->AddPath(dir, true); } } void QtStylePreferencePage::UpdatePathListButtons() { int s = controls.m_PathList->selectedItems().size(); if (s == 0) { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(false); } else if (s == 1) { controls.m_EditButton->setEnabled(true); controls.m_RemoveButton->setEnabled(true); } else { controls.m_EditButton->setEnabled(false); controls.m_RemoveButton->setEnabled(true); } } QWidget* QtStylePreferencePage::GetQtControl() const { return mainWidget; } bool QtStylePreferencePage::PerformOk() { auto* prefs = GetPreferences(); prefs->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString().toStdString()); QString paths; for (int i = 0; i < controls.m_PathList->count(); ++i) { QString path = controls.m_PathList->item(i)->text() + ";"; paths += path; } prefs->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths.toStdString()); prefs->Put(berry::QtPreferences::QT_FONT_NAME, controls.m_FontComboBox->currentText().toStdString()); prefs->Put(berry::QtPreferences::QT_FONT_SIZE, std::to_string(controls.m_FontSizeSpinBox->value())); prefs->PutBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, controls.m_ToolbarCategoryCheckBox->isChecked()); return true; } void QtStylePreferencePage::PerformCancel() { Update(); } void QtStylePreferencePage::Update() { styleManager->RemoveStyles(); auto* prefs = GetPreferences(); auto paths = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, "")); QStringList pathList = paths.split(";", Qt::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddPath(it.next(), false); } auto styleName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_NAME, "")); styleManager->SetStyle(styleName); oldStyle = styleManager->GetStyle(); FillStyleCombo(oldStyle); auto fontName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans")); styleManager->SetFont(fontName); auto fontSize = std::stoi(prefs->Get(berry::QtPreferences::QT_FONT_SIZE, "9")); styleManager->SetFontSize(fontSize); controls.m_FontSizeSpinBox->setValue(fontSize); styleManager->UpdateWorkbenchFont(); FillFontCombo(styleManager->GetFont()); controls.m_ToolbarCategoryCheckBox->setChecked( prefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true)); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp index bc82394674..a2bb630a98 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp @@ -1,159 +1,159 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include "berryRegistryReader.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" namespace { bool CompareExtensionsByContributor(const berry::IExtension::Pointer& e1, const berry::IExtension::Pointer& e2) { return e1->GetContributor()->GetName().compare(e2->GetContributor()->GetName(), Qt::CaseInsensitive) < 0; } } namespace berry { RegistryReader::RegistryReader() { } RegistryReader::~RegistryReader() { } void RegistryReader::LogError(const IConfigurationElement::Pointer& element, const QString& text) { IExtension::Pointer extension = element->GetDeclaringExtension(); QString buf = QString("Plugin ") + extension->GetContributor()->GetName() + ", extension " + extension->GetExtensionPointUniqueIdentifier(); // look for an ID if available - this should help debugging QString id = element->GetAttribute("id"); if (!id.isEmpty()) { buf.append(", id "); buf.append(id); } buf.append(": " + text); WorkbenchPlugin::Log(buf); } void RegistryReader::LogMissingAttribute( const IConfigurationElement::Pointer& element, const QString& attributeName) { RegistryReader::LogError(element, "Required attribute '" + attributeName + "' not defined"); } void RegistryReader::LogMissingElement( const IConfigurationElement::Pointer& element, const QString& elementName) { RegistryReader::LogError(element, "Required sub element '" + elementName + "' not defined"); } void RegistryReader::LogUnknownElement( const IConfigurationElement::Pointer& element) { RegistryReader::LogError(element, "Unknown extension tag found: " + element->GetName()); } QList RegistryReader::OrderExtensions( const QList& extensions) { // By default, the order is based on plugin id sorted // in ascending order. The order for a plugin providing // more than one extension for an extension point is // dependent in the order listed in the XML file. QList sortedExtension(extensions); - qStableSort(sortedExtension.begin(), sortedExtension.end(), + std::stable_sort(sortedExtension.begin(), sortedExtension.end(), CompareExtensionsByContributor); return sortedExtension; } void RegistryReader::ReadElementChildren( const IConfigurationElement::Pointer& element) { this->ReadElements(element->GetChildren()); } void RegistryReader::ReadElements( const QList& elements) { for (int i = 0; i < elements.size(); i++) { if (!this->ReadElement(elements[i])) { RegistryReader::LogUnknownElement(elements[i]); } } } void RegistryReader::ReadExtension(const IExtension::Pointer& extension) { this->ReadElements(extension->GetConfigurationElements()); } void RegistryReader::ReadRegistry(IExtensionRegistry* registry, const QString& pluginId, const QString& extensionPoint) { IExtensionPoint::Pointer point = registry->GetExtensionPoint(pluginId, extensionPoint); if (point == 0) { return; } QList extensions(point->GetExtensions()); extensions = this->OrderExtensions(extensions); for (int i = 0; i < extensions.size(); i++) { this->ReadExtension(extensions[i]); } } QString RegistryReader::GetDescription(const IConfigurationElement::Pointer& configElement) { QList children(configElement->GetChildren(WorkbenchRegistryConstants::TAG_DESCRIPTION)); if (children.size() >= 1) { return children[0]->GetValue(); } return ""; } QString RegistryReader::GetClassValue( const IConfigurationElement::Pointer& configElement, const QString& classAttributeName) { QString className = configElement->GetAttribute(classAttributeName); if (!className.isEmpty()) { return className; } QList candidateChildren(configElement->GetChildren(classAttributeName)); if (candidateChildren.isEmpty()) { return ""; } return candidateChildren[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp index e66d27ec25..6b1205498e 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp @@ -1,275 +1,275 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryShowViewMenu.h" #include #include #include #include #include #include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryViewDescriptor.h" #include "intro/berryIntroConstants.h" #include #include #include namespace berry { const QString ShowViewMenu::NO_TARGETS_MSG = ""; struct ActionComparator { bool operator()(const CommandContributionItemParameter::Pointer& p1, const CommandContributionItemParameter::Pointer& p2) const { return p1->label < p2->label; } }; ShowViewMenu::ShowViewMenu(IWorkbenchWindow *window, const QString& id) : ContributionItem(id), dirty(true), window(window) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( window, QString(), IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // window.getWorkbench().getHelpSystem().setHelp(showDlgAction, // IWorkbenchHelpContextIds.SHOW_VIEW_OTHER_ACTION); // // indicate that a show views submenu has been created // if (window instanceof WorkbenchWindow) { // ((WorkbenchWindow) window) // .addSubmenu(WorkbenchWindow.SHOW_VIEW_SUBMENU); // } } bool ShowViewMenu::IsDirty() const { return dirty; } /** * Overridden to always return true and force dynamic menu building. */ bool ShowViewMenu::IsDynamic() const { return true; } void ShowViewMenu::Fill(QMenu* menu, QAction* before) { if (MenuManager* mm = dynamic_cast(GetParent())) { this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); } if (!dirty) { return; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); if (items.isEmpty()) { auto action = new QAction(NO_TARGETS_MSG, menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { item->Fill(menu, before); } } dirty = false; } void ShowViewMenu::FillMenu(IMenuManager* innerMgr) { // Remove all. innerMgr->RemoveAll(); // If no page disable all. IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } // If no active perspective disable all if (page->GetPerspective().IsNull()) { return; } typedef QPair ViewIdPair; // Get visible actions. QSet viewIds = GetShortcuts(page.GetPointer()); // add all open views viewIds = AddOpenedViews(page.GetPointer(), viewIds); QList actions; foreach (ViewIdPair id, viewIds) { if (id.first == IntroConstants::INTRO_VIEW_ID) { continue; } CommandContributionItemParameter::Pointer item = GetItem(id.first, id.second); if (item) { actions.append(item); } } - qSort(actions.begin(), actions.end(), ActionComparator()); + std::sort(actions.begin(), actions.end(), ActionComparator()); foreach (CommandContributionItemParameter::Pointer ccip, actions) { // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); innerMgr->Add(item); } // We only want to add the separator if there are show view shortcuts, // otherwise, there will be a separator and then the 'Other...' entry // and that looks weird as the separator is separating nothing if (!innerMgr->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); innerMgr->Add(separator); } // Add Other... innerMgr->Add(showDlgItem); } QSet > ShowViewMenu::GetShortcuts(IWorkbenchPage* page) const { QSet > list; QList shortcuts(page->GetShowViewShortcuts()); for (int i = 0; i < shortcuts.size(); ++i) { list.insert(qMakePair(shortcuts[i], QString())); } return list; } void ShowViewMenu::AboutToShow(IMenuManager* manager) { manager->MarkDirty(); this->dirty = true; } CommandContributionItemParameter::Pointer ShowViewMenu::GetItem(const QString& viewId, const QString& secondaryId) const { IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(viewId); if (desc.IsNull()) { return CommandContributionItemParameter::Pointer(nullptr); } QString label = desc->GetLabel(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: typedef PluginCCIP Self; static const char* GetStaticClassName() { return "PluginCCIP"; } berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution) PluginCCIP(const IViewDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { ViewDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const override { return localId; } QString GetPluginId() const override { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, viewId, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); parms->label = label; parms->icon = desc->GetImageDescriptor(); Object::Pointer strViewId(new ObjectString(viewId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID, strViewId); // if (makeFast) // { // parms.parameters.put( // IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW, // "true"); //$NON-NLS-1$ // } if (!secondaryId.isEmpty()) { Object::Pointer strSecondaryId(new ObjectString(secondaryId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID, strSecondaryId); } return parms; } QSet > ShowViewMenu::AddOpenedViews(IWorkbenchPage* page, QSet >& actions) const { QSet > views = GetParts(page); return views.unite(actions); } QSet > ShowViewMenu::GetParts(IWorkbenchPage* page) const { QSet > parts; QList refs = page->GetViewReferences(); for (int i = 0; i < refs.size(); ++i) { parts.insert(qMakePair(refs[i]->GetId(), refs[i]->GetSecondaryId())); } return parts; } } diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp index 7b314e961f..ad0a0a8df1 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp +++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp @@ -1,292 +1,292 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryPerspectivesPreferencePage.h" #include "ui_berryPerspectivesPreferencePage.h" #include #include "internal/berryPerspective.h" #include "internal/berryPerspectiveRegistry.h" #include "internal/berryPreferenceConstants.h" #include "internal/berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" #include #include #include namespace { mitk::IPreferences* GetPreferences() { return berry::WorkbenchPlugin::GetDefault()->GetPreferences(); } } namespace berry { bool PerspectiveComparator(const PerspectiveDescriptor::Pointer& p1, const PerspectiveDescriptor::Pointer& p2) { return p1->GetLabel() < p2->GetLabel(); } PerspectivesPreferencePage::PerspectivesPreferencePage() : ui(nullptr) , pageWidget(nullptr) , workbench(nullptr) , perspRegistry(nullptr) { } PerspectivesPreferencePage::~PerspectivesPreferencePage() { delete ui; } void PerspectivesPreferencePage::Init(berry::IWorkbench::Pointer workbench) { ui = new Ui::PerspectivesPreferencePage; this->workbench = workbench.GetPointer(); perspRegistry = dynamic_cast(workbench->GetPerspectiveRegistry()); } void PerspectivesPreferencePage::CreateQtControl(QWidget* parent) { pageWidget = new QWidget(parent); ui->setupUi(pageWidget); ui->perspectivesListWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->perspectivesListWidget->setIconSize(QSize(16, 16)); connect(ui->sameWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInSameWindow())); connect(ui->newWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInNewWindow())); connect(ui->perspectivesListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(PerspectiveSelectionChanged())); connect(ui->revertButton, SIGNAL(clicked()), this, SLOT(RevertPerspective())); connect(ui->makeDefaultButton, SIGNAL(clicked()), this, SLOT(MakeDefaultPerspective())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(DeletePerspective())); this->Update(); } QWidget* PerspectivesPreferencePage::GetQtControl() const { return pageWidget; } bool PerspectivesPreferencePage::PerformOk() { // Set the default perspective if (defaultPerspectiveId != perspRegistry->GetDefaultPerspective()) { perspRegistry->SetDefaultPerspective(defaultPerspectiveId); } //Delete the perspective if(perspectives.size() < perspRegistry->GetPerspectives().size()) { QList windows = workbench->GetWorkbenchWindows(); // close any perspectives that are about to be deleted for (int i = 0; i < windows.size(); i++) { QList pages = windows[i]->GetPages(); for (int j = 0; j < pages.size(); j++) { WorkbenchPage::Pointer page = pages[j].Cast(); for (int k = 0; k < perspToDelete.size(); k++) { IPerspectiveDescriptor::Pointer desc(perspToDelete[k].GetPointer()); if (page->FindPerspective(desc).IsNotNull()) { page->ClosePerspective(desc, true, true); } } } } perspRegistry->DeletePerspectives(perspToDelete); } // Revert the perspectives perspRegistry->RevertPerspectives(perspToRevert); // store the open perspective mode setting auto* prefs = GetPreferences(); prefs->PutInt(PreferenceConstants::OPEN_PERSP_MODE, openPerspMode); return true; } void PerspectivesPreferencePage::PerformCancel() { } void PerspectivesPreferencePage::Update() { auto* prefs = GetPreferences(); openPerspMode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); ui->sameWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_ACTIVE_PAGE); ui->newWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_NEW_WINDOW); // Populate the perspectivesTable perspectives.clear(); perspToRevert.clear(); perspToDelete.clear(); QList persps = perspRegistry->GetPerspectives(); for (int i = 0; i < persps.size(); i++) { perspectives.push_back(persps[i].Cast()); } - qSort(perspectives.begin(), perspectives.end(), PerspectiveComparator); + std::sort(perspectives.begin(), perspectives.end(), PerspectiveComparator); defaultPerspectiveId = perspRegistry->GetDefaultPerspective(); UpdatePerspectivesTable(); } void PerspectivesPreferencePage::OpenPerspInSameWindow() { openPerspMode = PreferenceConstants::OPM_ACTIVE_PAGE; } void PerspectivesPreferencePage::OpenPerspInNewWindow() { openPerspMode = PreferenceConstants::OPM_NEW_WINDOW; } void PerspectivesPreferencePage::PerspectiveSelectionChanged() { UpdateButtons(); } void PerspectivesPreferencePage::RevertPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToRevert.contains(desc)) { perspToRevert.push_back(desc); } UpdateButtons(); } void PerspectivesPreferencePage::DeletePerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { if (!FindOpenInstance(desc)) { perspToDelete.push_back(desc); perspToRevert.removeAll(desc); perspectives.removeAll(desc); UpdatePerspectivesTable(); } } UpdateButtons(); } void PerspectivesPreferencePage::MakeDefaultPerspective() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc.IsNotNull() && !perspToDelete.contains(desc)) { int row = perspectives.indexOf(desc); defaultPerspectiveId = desc->GetId(); UpdatePerspectivesTable(); ui->perspectivesListWidget->item(row)->setSelected(true); } UpdateButtons(); } void PerspectivesPreferencePage::UpdateButtons() { PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); if (desc) { ui->revertButton->setEnabled(desc->IsPredefined() && desc->HasCustomDefinition() && !perspToRevert.contains(desc)); ui->deleteButton->setEnabled(!desc->IsPredefined()); ui->makeDefaultButton->setEnabled(true); } else { ui->revertButton->setEnabled(false); ui->deleteButton->setEnabled(false); ui->makeDefaultButton->setEnabled(false); } } void PerspectivesPreferencePage::UpdatePerspectivesTable() { ui->perspectivesListWidget->clear(); for (const PerspectiveDescriptor::Pointer &desc : qAsConst(perspectives)) { NewPerspectivesTableItem(desc); } } void PerspectivesPreferencePage::NewPerspectivesTableItem(const SmartPointer& desc) { QString label = desc->GetLabel(); if (desc->GetId() == defaultPerspectiveId) { label += " (default)"; } new QListWidgetItem(desc->GetImageDescriptor(), label, ui->perspectivesListWidget); } bool PerspectivesPreferencePage::FindOpenInstance(const PerspectiveDescriptor::Pointer& desc) { QList windows = workbench->GetWorkbenchWindows(); //find all active perspectives currently for (int i = 0; i < windows.size(); i++) { QList pages = windows[i]->GetPages(); for (int j = 0; j < pages.size(); j++) { WorkbenchPage::Pointer page = pages[j].Cast(); if (page->FindPerspective(desc).IsNotNull()) { QMessageBox::StandardButton returnCode = QMessageBox::question(workbench->GetActiveWorkbenchWindow()->GetShell()->GetControl(), "Delete Perspective", QString("Are you sure you want to delete the \"%1\" perspective? It has open instances.").arg(desc->GetLabel()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); return (returnCode != QMessageBox::Yes); } } } return false; } SmartPointer PerspectivesPreferencePage::GetSelectedPerspective() const { PerspectiveDescriptor::Pointer desc; QList selection = ui->perspectivesListWidget->selectedItems(); if (!selection.isEmpty()) { int row = ui->perspectivesListWidget->row(selection.back()); if (row > -1) { desc = perspectives.at(row); } } return desc; } } diff --git a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp index 8fe1f286e6..93d035151b 100644 --- a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp +++ b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp @@ -1,460 +1,461 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryViewTreeModel.h" #include "berryIViewRegistry.h" #include "berryIViewCategory.h" #include "berryIWorkbench.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "internal/intro/berryIntroConstants.h" #include "internal/berryKeywordRegistry.h" #include #include +#include namespace berry { // --------------------------- Tree Item Classes --------------------------- struct ViewTreeItem; bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2); struct ViewTreeItem { ViewTreeItem(ViewTreeModel* model) : m_parent(nullptr) , m_model(model) {} virtual ~ViewTreeItem() { QList children = m_children; if (m_parent) m_parent->removeChild(this); qDeleteAll(children); } virtual QVariant data(int role) { if (role == ViewTreeModel::Keywords) { if (m_keywordCache.isEmpty()) { m_keywordCache = keywordLabels().values(); } return m_keywordCache; } return QVariant(); } virtual Qt::ItemFlags flags() const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } virtual QSet keywordLabels() const { return QSet(); } void appendChild(ViewTreeItem* child) { m_children.push_back(child); child->m_parent = this; - qSort(m_children.begin(), m_children.end(), CompareViewTreeItem); + std::sort(m_children.begin(), m_children.end(), CompareViewTreeItem); } void removeChild(ViewTreeItem* child) { m_children.removeAll(child); } QList takeChildren() { QList children = m_children; m_children.clear(); return children; } ViewTreeItem* childItem(int row) const { if (row < 0 || row >= m_children.size()) return nullptr; return m_children.at(row); } ViewTreeItem* parentItem() const { return m_parent; } int childCount() const { return m_children.size(); } int row() const { if (m_parent) return m_parent->rowIndex(this); return 0; } int rowIndex(const ViewTreeItem* child) const { return m_children.indexOf(const_cast(child)); } QList m_children; ViewTreeItem* m_parent; ViewTreeModel* m_model; private: QStringList m_keywordCache; }; bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2) { return item1->data(Qt::DisplayRole).toString() < item2->data(Qt::DisplayRole).toString(); } struct RootTreeItem : ViewTreeItem { RootTreeItem(ViewTreeModel* model) : ViewTreeItem(model) {} QVariant data(int /*role*/) override { return QVariant(); } }; struct DescriptorTreeItem : ViewTreeItem { DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent = nullptr); QVariant data(int role) override; protected: QSet keywordLabels() const override; IViewDescriptor::Pointer m_descriptor; }; struct CategoryTreeItem : ViewTreeItem { CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent = nullptr); QVariant data(int role) override; Qt::ItemFlags flags() const override; protected: QSet keywordLabels() const override; /** * Removes the temporary intro view from the list so that it cannot be activated except through * the introduction command. */ void RemoveIntroView(QList& list); private: void CreateChildren(); IViewCategory::Pointer m_category; }; // --------------------------- Tree Model Classes --------------------------- struct ViewTreeModel::Impl { Impl(const IWorkbenchWindow* window) : window(window) , viewRegistry(*window->GetWorkbench()->GetViewRegistry()) { } const IWorkbenchWindow* window; IViewRegistry& viewRegistry; QScopedPointer rootItem; }; ViewTreeModel::ViewTreeModel(const IWorkbenchWindow* window, QObject* parent) : QAbstractItemModel(parent) , d(new Impl(window)) { d->rootItem.reset(new RootTreeItem(this)); QList categoryItems; QList categories = d->viewRegistry.GetCategories(); for (const auto &category : qAsConst(categories)) { if (category->GetViews().isEmpty()) continue; CategoryTreeItem* categoryItem = new CategoryTreeItem(this, category); if (categoryItem->childCount() == 0) { delete categoryItem; } else { categoryItems.push_back(categoryItem); } } // if there is only one category, return it's children directly if (categoryItems.size() == 1) { QList items = categoryItems.front()->takeChildren(); for (auto item : qAsConst(items)) { d->rootItem->appendChild(item); } qDeleteAll(categoryItems); } else { for (auto category : qAsConst(categoryItems)) { d->rootItem->appendChild(category); } } } ViewTreeModel::~ViewTreeModel() { } QVariant ViewTreeModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); return static_cast(index.internalPointer())->data(role); } Qt::ItemFlags ViewTreeModel::flags(const QModelIndex& index) const { if (!index.isValid()) return {}; return static_cast(index.internalPointer())->flags(); } QVariant ViewTreeModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const { if (role == Qt::DisplayRole && section == 0) { return "View"; } return QVariant(); } QModelIndex ViewTreeModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } ViewTreeItem* parentItem = nullptr; if (!parent.isValid()) { parentItem = d->rootItem.data(); } else { parentItem = static_cast(parent.internalPointer()); } ViewTreeItem* childItem = parentItem->childItem(row); if (childItem) { return createIndex(row, column, childItem); } return QModelIndex(); } QModelIndex ViewTreeModel::parent(const QModelIndex& child) const { if (!child.isValid()) { return QModelIndex(); } ViewTreeItem* childItem = static_cast(child.internalPointer()); ViewTreeItem* parentItem = childItem->parentItem(); if (parentItem == d->rootItem.data()) { return QModelIndex(); } return createIndex(parentItem->row(), 0, parentItem); } int ViewTreeModel::rowCount(const QModelIndex& parent) const { ViewTreeItem* parentItem = nullptr; if (parent.column() > 0) return 0; if (!parent.isValid()) { parentItem = d->rootItem.data(); } else { parentItem = static_cast(parent.internalPointer()); } return parentItem->childCount(); } int ViewTreeModel::columnCount(const QModelIndex& /*parent*/) const { return 1; } const IWorkbenchWindow*ViewTreeModel::GetWorkbenchWindow() const { return d->window; } // --------------------------- DescriptorTreeItem --------------------------- DescriptorTreeItem::DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent) : ViewTreeItem(model) , m_descriptor(descriptor) { if (parent) parent->appendChild(this); } QVariant DescriptorTreeItem::data(int role) { if (role == Qt::DisplayRole) { return m_descriptor->GetLabel(); } else if (role == Qt::DecorationRole) { return m_descriptor->GetImageDescriptor(); } else if (role == Qt::ForegroundRole) { IWorkbenchPage::Pointer page = this->m_model->GetWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { if (page->FindViewReference(m_descriptor->GetId()).IsNotNull()) { return QBrush(QColor(Qt::gray)); } } } else if (role == ViewTreeModel::Description) { return m_descriptor->GetDescription(); } else if (role == ViewTreeModel::Id) { return m_descriptor->GetId(); } return ViewTreeItem::data(role); } QSet DescriptorTreeItem::keywordLabels() const { KeywordRegistry* registry = KeywordRegistry::GetInstance(); QStringList ids = m_descriptor->GetKeywordReferences(); QSet keywords; keywords.insert(m_descriptor->GetLabel()); for(const auto &id : qAsConst(ids)) { QString label = registry->GetKeywordLabel(id); for (const auto &keyword : label.split(' ', Qt::SkipEmptyParts)) { keywords.insert(keyword); } } return keywords; } // --------------------------- CategoryTreeItem --------------------------- CategoryTreeItem::CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent) : ViewTreeItem(model) , m_category(category) { if (parent) parent->appendChild(this); this->CreateChildren(); } QVariant CategoryTreeItem::data(int role) { if (role == Qt::DisplayRole) { return m_category->GetLabel(); } else if (role == Qt::DecorationRole) { return QIcon::fromTheme("folder"); } else if (role == ViewTreeModel::Id) { return m_category->GetId(); } return ViewTreeItem::data(role); } Qt::ItemFlags CategoryTreeItem::flags() const { return Qt::ItemIsEnabled; } QSet CategoryTreeItem::keywordLabels() const { QSet keywords; for(auto child : this->m_children) { for (const auto &keyword : child->data(ViewTreeModel::Keywords).toStringList()) { keywords.insert(keyword); } } return keywords; } void CategoryTreeItem::CreateChildren() { auto viewDescriptors = m_category->GetViews(); RemoveIntroView(viewDescriptors); for(const auto &viewDescriptor : qAsConst(viewDescriptors)) { new DescriptorTreeItem(this->m_model, viewDescriptor, this); } } void CategoryTreeItem::RemoveIntroView(QList& list) { for (auto view = list.begin(); view != list.end();) { if ((*view)->GetId() == IntroConstants::INTRO_VIEW_ID) { view = list.erase(view); } else ++view; } } } diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp index 44be82cacb..e4a7686adf 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp @@ -1,729 +1,729 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // View navigator plugin #include #include #include // Blueberry #include #include #include #include #include #include #include #include // MITK #include // Qt #include #include #include #include #include namespace { QFont getLargeFont() { QFont font = qApp->font(); font.setPointSizeF(font.pointSizeF() * 1.25f); return font; } } class KeywordRegistry { public: KeywordRegistry() { berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords"); for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); QString keywordLabels = (*keywordExtsIt)->GetAttribute("label"); m_Keywords[keywordId].push_back(keywordLabels); } } QStringList GetKeywords(const QString& id) { return m_Keywords[id]; } QStringList GetKeywords(const QStringList& ids) { QStringList result; for (const auto& id : ids) { result.append(this->GetKeywords(id)); } return result; } private: QHash m_Keywords; }; class ClassFilterProxyModel : public QSortFilterProxyModel { public: ClassFilterProxyModel(QObject* parent = nullptr) : QSortFilterProxyModel(parent) { } bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return hasToBeDisplayed(index); } private: bool displayElement(const QModelIndex index) const { QString type = sourceModel()->data(index, Qt::DisplayRole).toString(); QStandardItem* item = dynamic_cast(sourceModel())->itemFromIndex(index); if (type.contains(filterRegularExpression())) { return true; } QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { for (const auto& tag : viewItem->m_Tags) { if (tag.contains(filterRegularExpression())) { return true; } } if (viewItem->m_Description.contains(filterRegularExpression())) { return true; } } QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { for (const auto& tag : perspectiveItem->m_Tags) { if (tag.contains(filterRegularExpression())) { return true; } } if (perspectiveItem->m_Description.contains(filterRegularExpression())) { return true; } } return false; } bool hasToBeDisplayed(const QModelIndex index) const { bool result = false; if (sourceModel()->rowCount(index) > 0) { for (int i = 0; i < sourceModel()->rowCount(index); i++) { QModelIndex childIndex = sourceModel()->index(i, 0, index); if (!childIndex.isValid()) { break; } result = hasToBeDisplayed(childIndex); result |= displayElement(index); if (result) { break; } } } else { result = displayElement(index); } return result; } }; class ViewNavigatorPerspectiveListener: public berry::IPerspectiveListener { public: ViewNavigatorPerspectiveListener(QmitkViewNavigatorWidget* parent) : m_ParentWidget(parent) { } Events::Types GetPerspectiveEventTypes() const override { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED | Events::PART_CHANGED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->m_ActivePerspective = nullptr; } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->UpdateTreeList(); } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override { m_ParentWidget->m_ActivePerspective = nullptr; } using IPerspectiveListener::PerspectiveChanged; void PerspectiveChanged(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/, const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId) { if (changeId == "viewHide" && partRef->GetId() == "org.mitk.views.viewnavigator") berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(m_ParentWidget->m_PerspectiveListener.data()); else m_ParentWidget->UpdateTreeList(); } private: QmitkViewNavigatorWidget* m_ParentWidget; }; class ViewNavigatorViewListener: public berry::IPartListener { public: ViewNavigatorViewListener(QmitkViewNavigatorWidget* parent) : m_ParentWidget(parent) { } Events::Types GetPartEventTypes() const override { return Events::OPENED | Events::CLOSED; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override { if (partRef->GetId() != "org.mitk.views.viewnavigator") { m_ParentWidget->UpdateTreeList((partRef->GetPart(false)).GetPointer()); } else { m_ParentWidget->FillTreeList(); m_ParentWidget->UpdateTreeList(); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override { if (partRef->GetId() != "org.mitk.views.viewnavigator") { m_ParentWidget->UpdateTreeList(); } } private: QmitkViewNavigatorWidget* m_ParentWidget; }; bool compareViews(const berry::IViewDescriptor::Pointer& a, const berry::IViewDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) { return false; } return a->GetLabel().compare(b->GetLabel()) < 0; } bool comparePerspectives(const berry::IPerspectiveDescriptor::Pointer& a, const berry::IPerspectiveDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) { return false; } return a->GetLabel().compare(b->GetLabel()) < 0; } bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b) { if (nullptr == a || nullptr== b) { return false; } return a->text().compare(b->text()) < 0; } QmitkViewNavigatorWidget::QmitkViewNavigatorWidget(berry::IWorkbenchWindow::Pointer window, QWidget* parent, Qt::WindowFlags) : QWidget(parent) , m_Window(window) { this->CreateQtPartControl(this); } QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget() { m_Window->RemovePerspectiveListener(m_PerspectiveListener.data()); m_Window->GetPartService()->RemovePartListener(m_ViewPartListener.data()); } void QmitkViewNavigatorWidget::SetFocus() { m_Controls.lineEdit->setFocus(); } void QmitkViewNavigatorWidget::UpdateTreeList(berry::IWorkbenchPart* workbenchPart) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); if (page.IsNull()) { return; } m_ActivePerspective = page->GetPerspective(); QList viewParts = page->GetViews(); // iterate over all tree items for (const auto& item : m_TreeModel->findItems("*", Qt::MatchWildcard | Qt::MatchRecursive)) { QFont font = qApp->font(); // check if the item is a view item and if it is equal to any opened view QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { if (nullptr != workbenchPart && workbenchPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel()) { font.setBold(true); } else { for (const auto& viewPart : viewParts) { if (viewPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel()) { font.setBold(true); break; } } } viewItem->setFont(font); } else { // check if the item is a perspective item and if it is equal to the current perspective QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { if (m_ActivePerspective.IsNotNull() && m_ActivePerspective->GetId() == perspectiveItem->m_ItemDescriptor->GetId()) { font.setBold(true); } perspectiveItem->setFont(font); } } } } bool QmitkViewNavigatorWidget::FillTreeList() { // initialize tree model m_TreeModel->clear(); // add all available views this->AddViewsToTree(); // add all available perspectives this->AddPerspectivesToTree(); m_Controls.m_PluginTreeView->expandAll(); return true; } void QmitkViewNavigatorWidget::FilterChanged() { QString filterString = m_Controls.lineEdit->text(); m_Controls.m_PluginTreeView->expandAll(); QString strPattern = "^*" + filterString; QRegularExpression regExp(strPattern, QRegularExpression::CaseInsensitiveOption); m_FilterProxyModel->setFilterRegularExpression(regExp); } void QmitkViewNavigatorWidget::ItemClicked(const QModelIndex &index) { QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { try { berry::PlatformUI::GetWorkbench()->ShowPerspective( perspectiveItem->m_ItemDescriptor->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } catch (...) { QMessageBox::critical(nullptr, "Opening Perspective Failed", QString("The requested perspective could not be opened.\nSee the log for details.")); } return; } QmitkViewItem* viewItem = dynamic_cast(item); if (nullptr != viewItem) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { try { page->ShowView(viewItem->m_ItemDescriptor->GetId()); } catch (const berry::PartInitException& e) { BERRY_ERROR << "Error: " << e.what() << std::endl; } } } } void QmitkViewNavigatorWidget::SaveCurrentPerspectiveAs() { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer currentPerspective = page->GetPerspective(); bool ok = false; QString perspectiveLabel = QInputDialog::getText(this, "Save perspective as ...", "New perspective name:", QLineEdit::Normal, "", &ok); if (!ok) { return; } if (perspectiveLabel.isEmpty()) { QMessageBox::information(this, "Save perspective as ...", "Please select a valid perspective name."); return; } berry::IPerspectiveRegistry* perspectiveRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); berry::IPerspectiveDescriptor::Pointer newPerspective = perspectiveRegistry->CreatePerspective(perspectiveLabel, currentPerspective); if (nullptr == newPerspective) { QMessageBox::information(this, "Save perspective as ...", "The selected perspective name is already in use."); return; } page->SavePerspectiveAs(newPerspective); this->FillTreeList(); this->UpdateTreeList(); } void QmitkViewNavigatorWidget::ResetCurrentPerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to reset the current perspective?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->ResetPerspective(); } } void QmitkViewNavigatorWidget::ClosePerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close the current perspective?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } } void QmitkViewNavigatorWidget::CloseAllPerspectives() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close all perspectives?", QMessageBox::Yes | QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); page->CloseAllPerspectives(true, true); } } void QmitkViewNavigatorWidget::ExpandAll() { m_Controls.m_PluginTreeView->expandAll(); } void QmitkViewNavigatorWidget::CollapseAll() { m_Controls.m_PluginTreeView->collapseAll(); } void QmitkViewNavigatorWidget::CustomMenuRequested(QPoint pos) { QModelIndex index = m_Controls.m_PluginTreeView->indexAt(pos); QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if (nullptr == m_ContextMenu) return; m_ContextMenu->clear(); QmitkPerspectiveItem* perspectiveItem = dynamic_cast(item); if (nullptr != perspectiveItem) { berry::IPerspectiveDescriptor::Pointer perspectiveDescriptor = perspectiveItem->m_ItemDescriptor; if (this->m_ActivePerspective.IsNotNull() && this->m_ActivePerspective == perspectiveDescriptor) { QAction* saveAsAction = new QAction("Save perspective as ...", this); m_ContextMenu->addAction(saveAsAction); connect(saveAsAction, SIGNAL(triggered()), SLOT(SaveCurrentPerspectiveAs())); m_ContextMenu->addSeparator(); } } QAction* resetAction = new QAction("Reset current perspective", this); m_ContextMenu->addAction(resetAction); connect(resetAction, SIGNAL(triggered()), SLOT(ResetCurrentPerspective())); QAction* closeAction = new QAction("Close perspective", this); m_ContextMenu->addAction(closeAction); connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective())); QAction* closeAllAction = new QAction("Close all perspectives", this); m_ContextMenu->addAction(closeAllAction); connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives())); m_ContextMenu->addSeparator(); QAction* expandAction = new QAction("Expand tree", this); m_ContextMenu->addAction(expandAction); connect(expandAction, SIGNAL(triggered()), SLOT(ExpandAll())); QAction* collapseAction = new QAction("Collapse tree", this); m_ContextMenu->addAction(collapseAction); connect(collapseAction, SIGNAL(triggered()), SLOT(CollapseAll())); m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos)); } void QmitkViewNavigatorWidget::CreateQtPartControl(QWidget* parent) { // active workbench window available? if (m_Window.IsNull()) { return; } m_Controls.setupUi(parent); connect(m_Controls.m_PluginTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(CustomMenuRequested(QPoint))); connect(m_Controls.m_PluginTreeView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(ItemClicked(const QModelIndex&))); connect(m_Controls.lineEdit, SIGNAL(textChanged(QString)), SLOT(FilterChanged())); m_ContextMenu = new QMenu(m_Controls.m_PluginTreeView); m_Controls.m_PluginTreeView->setContextMenuPolicy(Qt::CustomContextMenu); // Create a new TreeModel for the data m_TreeModel = new QStandardItemModel(); m_FilterProxyModel = new ClassFilterProxyModel(this); m_FilterProxyModel->setSourceModel(m_TreeModel); m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel); m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); m_Window->AddPerspectiveListener(m_PerspectiveListener.data()); m_ViewPartListener.reset(new ViewNavigatorViewListener(this)); m_Window->GetPartService()->AddPartListener(m_ViewPartListener.data()); } void QmitkViewNavigatorWidget::AddPerspectivesToTree() { berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); QList perspectiveDescriptors(perspRegistry->GetPerspectives()); - qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); + std::sort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); QStandardItem* perspectiveRootItem = new QStandardItem("Perspectives"); perspectiveRootItem->setFont(getLargeFont()); perspectiveRootItem->setEditable(false); QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem(); treeRootItem->appendRow(perspectiveRootItem); this->AddItemsToTree, QmitkPerspectiveItem>( perspectiveDescriptors, perspectiveRootItem); } void QmitkViewNavigatorWidget::AddViewsToTree() { berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); QList viewDescriptors(viewRegistry->GetViews()); - qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); + std::sort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); auto largeFont = getLargeFont(); QStandardItem* viewRootItem = new QStandardItem("Views"); viewRootItem->setFont(largeFont); viewRootItem->setEditable(false); QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem(); treeRootItem->appendRow(viewRootItem); QStandardItem* miscellaneousCategoryItem = new QStandardItem("Miscellaneous"); miscellaneousCategoryItem->setFont(largeFont); miscellaneousCategoryItem->setEditable(false); QStringList viewExcludeList; // internal view used for the intro screen, will crash when opened directly, see T22352 viewExcludeList.append(QString("org.blueberry.ui.internal.introview")); viewExcludeList.append(QString("org.mitk.views.controlvisualizationpropertiesview")); viewExcludeList.append(QString("org.mitk.views.modules")); viewExcludeList.append(QString("org.mitk.views.viewnavigator")); this->AddItemsToTree, QmitkViewItem>( viewDescriptors, viewRootItem, miscellaneousCategoryItem, viewExcludeList); } template void QmitkViewNavigatorWidget::AddItemsToTree(D itemDescriptors, QStandardItem* rootItem, QStandardItem* miscellaneousItem, const QStringList& itemExcludeList) { KeywordRegistry keywordRegistry; std::vector categoryItems; for (const auto& itemDescriptor : itemDescriptors) { bool excludeView = itemExcludeList.contains(itemDescriptor->GetId()); if (excludeView) { continue; } QIcon icon = itemDescriptor->GetImageDescriptor(); I* item = new I(icon, itemDescriptor->GetLabel()); item->m_ItemDescriptor = itemDescriptor; item->m_Description = itemDescriptor->GetDescription(); item->setToolTip(itemDescriptor->GetDescription()); QStringList keylist = itemDescriptor->GetKeywordReferences(); item->m_Tags = keywordRegistry.GetKeywords(keylist); item->setEditable(false); QStringList categoryPath = itemDescriptor->GetCategoryPath(); if (categoryPath.empty()) { // If a root item for general / non-categorized item views is given, use it. // Otherwise put the non-categorized item views into the top root item. if (nullptr != miscellaneousItem) { miscellaneousItem->appendRow(item); } else { rootItem->appendRow(item); } } else { QStandardItem* categoryItem = nullptr; for (const auto& currentCategoryItem : categoryItems) { if (currentCategoryItem->text() == categoryPath.front()) { categoryItem = currentCategoryItem; break; } } if (nullptr == categoryItem) { categoryItem = new QStandardItem(QIcon(), categoryPath.front()); categoryItems.push_back(categoryItem); } auto font = getLargeFont(); categoryItem->setFont(font); categoryItem->setEditable(false); categoryItem->appendRow(item); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (const auto& categoryItem : categoryItems) { rootItem->appendRow(categoryItem); } if (nullptr != miscellaneousItem && miscellaneousItem->hasChildren()) { rootItem->appendRow(miscellaneousItem); } }