diff --git a/Applications/CoreApp/MitkCoreApp.cpp b/Applications/CoreApp/MitkCoreApp.cpp index 8f02537b8d..e3c6e1168c 100644 --- a/Applications/CoreApp/MitkCoreApp.cpp +++ b/Applications/CoreApp/MitkCoreApp.cpp @@ -1,93 +1,91 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include class QSafeApplication : public QApplication { public: QSafeApplication(int& argc, char** argv) : QApplication(argc, argv) {} /** * Reimplement notify to catch unhandled exceptions and open an error message. * * @param receiver * @param event * @return */ bool notify(QObject* receiver, QEvent* event) { QString msg; try { return QApplication::notify(receiver, event); } catch (Poco::Exception& e) { msg = QString::fromStdString(e.displayText()); } catch (std::exception& e) { msg = e.what(); } catch (...) { msg = "Unknown exception"; } QString text( "An error occurred. You should save all data and quit the program to prevent possible data loss.\nSee the error log for details.\n\n"); text += msg; QMessageBox::critical(0, "Error", text); return false; } }; int main(int argc, char** argv) { QSafeApplication safeApp(argc, argv); safeApp.setApplicationName("MitkCoreApp"); safeApp.setOrganizationName("DKFZ"); // These paths replace the .ini file and are tailored for installation // packages created with CPack. If a .ini file is presented, it will // overwrite the settings in MapConfiguration - Poco::Path basePath(argv[0]); - basePath.setFileName(""); + QDir basePath(argv[0]); - Poco::Path provFile(basePath); - provFile.setFileName("MitkCoreApp.provisioning"); + QString provFile = basePath.absoluteFilePath("MitkCoreApp.provisioning"); Poco::Util::MapConfiguration* coreConfig(new Poco::Util::MapConfiguration()); - coreConfig->setString(berry::Platform::ARG_PROVISIONING, provFile.toString()); - coreConfig->setString(berry::Platform::ARG_APPLICATION, "org.mitk.qt.coreapplication"); + coreConfig->setString(berry::Platform::ARG_PROVISIONING.toStdString(), provFile.toStdString()); + coreConfig->setString(berry::Platform::ARG_APPLICATION.toStdString(), "org.mitk.qt.coreapplication"); // Preload the org.mitk.gui.qt.common plug-in (and hence also Qmitk) to speed // up a clean-cache start. This also works around bugs in older gcc and glibc implementations, // which have difficulties with multiple dynamic opening and closing of shared libraries with // many global static initializers. It also helps if dependent libraries have weird static // initialization methods and/or missing de-initialization code. - coreConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY, "liborg_mitk_gui_qt_common"); + coreConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY.toStdString(), "liborg_mitk_gui_qt_common"); return berry::Starter::Run(argc, argv, coreConfig); } diff --git a/Applications/Diffusion/MitkDiffusion.cpp b/Applications/Diffusion/MitkDiffusion.cpp index 532034a804..77b5b80643 100644 --- a/Applications/Diffusion/MitkDiffusion.cpp +++ b/Applications/Diffusion/MitkDiffusion.cpp @@ -1,186 +1,186 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include #include #include +#include +#include class QtSafeApplication : public QtSingleApplication { public: QtSafeApplication(int& argc, char** argv) : QtSingleApplication(argc, argv) {} /** * Reimplement notify to catch unhandled exceptions and open an error message. * * @param receiver * @param event * @return */ bool notify(QObject* receiver, QEvent* event) { QString msg; try { return QApplication::notify(receiver, event); } catch (Poco::Exception& e) { msg = QString::fromStdString(e.displayText()); } catch (std::exception& e) { msg = e.what(); } catch (...) { msg = "Unknown exception"; } QString text("An error occurred. You should save all data and quit the program to " "prevent possible data loss.\nSee the error log for details.\n\n"); text += msg; QMessageBox::critical(0, "Error", text); return false; } }; int main(int argc, char** argv) { // Create a QApplication instance first QtSafeApplication qSafeApp(argc, argv); qSafeApp.setApplicationName("MitkDiffusion"); qSafeApp.setOrganizationName("DKFZ"); bool showSplashScreen(true); QPixmap pixmap( ":/splash/splashscreen.png" ); QSplashScreen splash( pixmap ); splash.setMask( pixmap.mask() ); splash.setWindowFlags( Qt::SplashScreen | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint ); if (showSplashScreen) { splash.show(); qSafeApp.sendPostedEvents(); qSafeApp.processEvents(); qSafeApp.flush(); QTimer::singleShot(4000, &splash, SLOT(close()) ); } // This function checks if an instance is already running // and either sends a message to it (containing the command // line arguments) or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. // In the latter case, a path to a temporary directory for // the new application's storage directory is returned. QString storageDir = handleNewAppInstance(&qSafeApp, argc, argv, "BlueBerry.newInstance"); // These paths replace the .ini file and are tailored for installation // packages created with CPack. If a .ini file is presented, it will // overwrite the settings in MapConfiguration - Poco::Path basePath(argv[0]); - basePath.setFileName(""); + QDir basePath(argv[0]); - Poco::Path provFile(basePath); - provFile.setFileName("MitkDiffusion.provisioning"); + QString provFile = basePath.absoluteFilePath("MitkDiffusion.provisioning"); Poco::Util::MapConfiguration* diffConfig(new Poco::Util::MapConfiguration()); if (!storageDir.isEmpty()) { - diffConfig->setString(berry::Platform::ARG_STORAGE_DIR, storageDir.toStdString()); + diffConfig->setString(berry::Platform::ARG_STORAGE_DIR.toStdString(), storageDir.toStdString()); } - diffConfig->setString(berry::Platform::ARG_PROVISIONING, provFile.toString()); - diffConfig->setString(berry::Platform::ARG_APPLICATION, "org.mitk.qt.diffusionimagingapp"); + diffConfig->setString(berry::Platform::ARG_PROVISIONING.toStdString(), provFile.toStdString()); + diffConfig->setString(berry::Platform::ARG_APPLICATION.toStdString(), "org.mitk.qt.diffusionimagingapp"); QStringList preloadLibs; // Preload the org.mitk.gui.qt.ext plug-in (and hence also QmitkExt) to speed // up a clean-cache start. This also works around bugs in older gcc and glibc implementations, // which have difficulties with multiple dynamic opening and closing of shared libraries with // many global static initializers. It also helps if dependent libraries have weird static // initialization methods and/or missing de-initialization code. preloadLibs << "liborg_mitk_gui_qt_ext"; QMap preloadLibVersion; #ifdef Q_OS_MAC const QString libSuffix = ".dylib"; #elif defined(Q_OS_UNIX) const QString libSuffix = ".so"; #elif defined(Q_OS_WIN) const QString libSuffix = ".dll"; #else const QString libSuffix; #endif for (QStringList::Iterator preloadLibIter = preloadLibs.begin(), iterEnd = preloadLibs.end(); preloadLibIter != iterEnd; ++preloadLibIter) { QString& preloadLib = *preloadLibIter; // In case the application is started from an install directory QString tempLibraryPath = QCoreApplication::applicationDirPath() + "/plugins/" + preloadLib + libSuffix; QFile preloadLibrary (tempLibraryPath); #ifdef Q_OS_MAC if (!preloadLibrary.exists()) { // In case the application is started from a build tree QString relPath = "/../../../plugins/" + preloadLib + libSuffix; tempLibraryPath = QCoreApplication::applicationDirPath() + relPath; preloadLibrary.setFileName(tempLibraryPath); } #endif if(preloadLibrary.exists()) { preloadLib = tempLibraryPath; } // Else fall back to the QLibrary search logic } QString preloadConfig; Q_FOREACH(const QString& preloadLib, preloadLibs) { preloadConfig += preloadLib + preloadLibVersion[preloadLib] + ","; } preloadConfig.chop(1); - diffConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY, preloadConfig.toStdString()); + diffConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY.toStdString(), preloadConfig.toStdString()); // Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); return berry::Starter::Run(argc, argv, diffConfig); } diff --git a/Applications/Workbench/MitkWorkbench.cpp b/Applications/Workbench/MitkWorkbench.cpp index 0e2df976a4..7490daa4cb 100644 --- a/Applications/Workbench/MitkWorkbench.cpp +++ b/Applications/Workbench/MitkWorkbench.cpp @@ -1,211 +1,214 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include #include #include +#include +#include +#include #include #include #include class QtSafeApplication : public QtSingleApplication { public: QtSafeApplication(int& argc, char** argv) : QtSingleApplication(argc, argv) {} /** * Reimplement notify to catch unhandled exceptions and open an error message. * * @param receiver * @param event * @return */ bool notify(QObject* receiver, QEvent* event) { QString msg; try { return QApplication::notify(receiver, event); } catch (mitk::Exception& e) { msg = QString("MITK Exception:\n\n") + QString("Description: ") + QString(e.GetDescription()) + QString("\n\n") + QString("Filename: ") + QString(e.GetFile()) + QString("\n\n") + QString("Line: ") + QString::number(e.GetLine()); } catch (Poco::Exception& e) { msg = QString::fromStdString(e.displayText()); } catch (std::exception& e) { msg = e.what(); } catch (...) { msg = "Unknown exception"; } MITK_ERROR << "An error occurred: " << msg.toStdString(); QMessageBox msgBox; msgBox.setText("An error occurred. You should save all data and quit the program to prevent possible data loss."); msgBox.setDetailedText(msg); msgBox.setIcon(QMessageBox::Critical); msgBox.addButton(trUtf8("Exit immediately"), QMessageBox::YesRole); msgBox.addButton(trUtf8("Ignore"), QMessageBox::NoRole); int ret = msgBox.exec(); switch(ret) { case 0: MITK_ERROR << "The program was closed."; this->closeAllWindows(); break; case 1: MITK_ERROR << "The error was ignored by the user. The program may be in a corrupt state and don't behave like expected!"; break; } return false; } }; int main(int argc, char** argv) { // Create a QApplication instance first QtSafeApplication qSafeApp(argc, argv); qSafeApp.setApplicationName("MITK Workbench"); qSafeApp.setOrganizationName("DKFZ"); // This function checks if an instance is already running // and either sends a message to it (containing the command // line arguments) or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. // In the latter case, a path to a temporary directory for // the new application's storage directory is returned. QString storageDir = handleNewAppInstance(&qSafeApp, argc, argv, "BlueBerry.newInstance"); if (storageDir.isEmpty()) { // This is a new instance and no other instance is already running. We specify // the storage directory here (this is the same code as in berryInternalPlatform.cpp // so that we can re-use the location for the persistent data location of the // the CppMicroServices library. // 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. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) storageDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '_'; #else storageDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + '_'; #endif storageDir += QString::number(qHash(QCoreApplication::applicationDirPath())) + QDir::separator(); } us::ModuleSettings::SetStoragePath((storageDir + QString("us") + QDir::separator()).toStdString()); // These paths replace the .ini file and are tailored for installation // packages created with CPack. If a .ini file is presented, it will // overwrite the settings in MapConfiguration QDir basePath(argv[0]); QString provFile = basePath.absoluteFilePath("MitkWorkbench.provisioning"); Poco::Util::MapConfiguration* extConfig(new Poco::Util::MapConfiguration()); if (!storageDir.isEmpty()) { extConfig->setString(berry::Platform::ARG_STORAGE_DIR.toStdString(), storageDir.toStdString()); } extConfig->setString(berry::Platform::ARG_PROVISIONING.toStdString(), provFile.toStdString()); extConfig->setString(berry::Platform::ARG_APPLICATION.toStdString(), "org.mitk.qt.extapplication"); QStringList preloadLibs; // Preload the org.mitk.gui.qt.ext plug-in (and hence also QmitkExt) to speed // up a clean-cache start. This also works around bugs in older gcc and glibc implementations, // which have difficulties with multiple dynamic opening and closing of shared libraries with // many global static initializers. It also helps if dependent libraries have weird static // initialization methods and/or missing de-initialization code. preloadLibs << "liborg_mitk_gui_qt_ext"; QMap preloadLibVersion; #ifdef Q_OS_MAC const QString libSuffix = ".dylib"; #elif defined(Q_OS_UNIX) const QString libSuffix = ".so"; #elif defined(Q_OS_WIN) const QString libSuffix = ".dll"; #else const QString libSuffix; #endif for (QStringList::Iterator preloadLibIter = preloadLibs.begin(), iterEnd = preloadLibs.end(); preloadLibIter != iterEnd; ++preloadLibIter) { QString& preloadLib = *preloadLibIter; // In case the application is started from an install directory QString tempLibraryPath = QCoreApplication::applicationDirPath() + "/plugins/" + preloadLib + libSuffix; QFile preloadLibrary (tempLibraryPath); #ifdef Q_OS_MAC if (!preloadLibrary.exists()) { // In case the application is started from a build tree QString relPath = "/../../../plugins/" + preloadLib + libSuffix; tempLibraryPath = QCoreApplication::applicationDirPath() + relPath; preloadLibrary.setFileName(tempLibraryPath); } #endif if(preloadLibrary.exists()) { preloadLib = tempLibraryPath; } // Else fall back to the QLibrary search logic } QString preloadConfig; Q_FOREACH(const QString& preloadLib, preloadLibs) { preloadConfig += preloadLib + preloadLibVersion[preloadLib] + ","; } preloadConfig.chop(1); extConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY.toStdString(), preloadConfig.toStdString()); // Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // Run the workbench. return berry::Starter::Run(argc, argv, extConfig); } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake index dc7bc9f4da..a38c51dd5b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake @@ -1,58 +1,59 @@ set(MOC_H_FILES + src/internal/berryExpressionPlugin.h ) set(CACHED_RESOURCE_FILES plugin.xml ) set(SRC_CPP_FILES berryElementHandler.cpp berryEvaluationContext.cpp berryEvaluationResult.cpp berryExpression.cpp berryExpressionConverter.cpp berryExpressionInfo.cpp berryExpressionTagNames.cpp berryICountable.h berryIEvaluationContext.cpp berryIIterable.cpp berryIPropertyTester.cpp berryIVariableResolver.cpp berryPropertyTester.cpp ) set(INTERNAL_CPP_FILES berryAdaptExpression.cpp berryAndExpression.cpp berryCompositeExpression.cpp berryCountExpression.cpp berryDefaultVariable.cpp berryDefinitionRegistry.cpp berryEnablementExpression.cpp berryEqualsExpression.cpp berryExpressionPlugin.cpp berryExpressions.cpp berryExpressionStatus.cpp berryInstanceofExpression.cpp berryIterateExpression.cpp berryNotExpression.cpp berryOrExpression.cpp berryProperty.cpp berryPropertyTesterDescriptor.cpp berryReferenceExpression.cpp berryResolveExpression.cpp berryStandardElementHandler.cpp berrySystemTestExpression.cpp berryTestExpression.cpp berryTypeExtension.cpp berryTypeExtensionManager.cpp berryWithExpression.cpp ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt index 064c8c58eb..2944414751 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt @@ -1,34 +1,38 @@ project(org_blueberry_core_runtime) set(QT_USE_QTXML 1) MACRO_CREATE_CTK_PLUGIN(EXPORT_DIRECTIVE org_blueberry_core_runtime_EXPORT EXPORTED_INCLUDE_SUFFIXES src src/application src/service src/registry) +target_link_libraries(${PLUGIN_TARGET} PUBLIC Poco::Foundation Poco::Util Poco::XML) + +# Set compiler flags +target_compile_definitions(${PLUGIN_TARGET} PUBLIC "$<$:POCO_NO_UNWINDOWS;WIN32_LEAN_AND_MEAN>") + add_executable(${OSGI_APP} MACOSX_BUNDLE "src/application/berryMain.cpp") -target_link_libraries(${OSGI_APP} ${PROJECT_NAME} mbilog) +target_link_libraries(${OSGI_APP} PRIVATE ${PROJECT_NAME} mbilog) if(_ctk_test_plugins) add_dependencies(${OSGI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_APP}) set_property(TARGET ${OSGI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_APP}.ini) add_executable(${OSGI_UI_APP} MACOSX_BUNDLE "src/application/berryMainUI.cpp") -target_link_libraries(${OSGI_UI_APP} ${PROJECT_NAME} mbilog) +target_link_libraries(${OSGI_UI_APP} PRIVATE ${PROJECT_NAME} mbilog) if(_ctk_test_plugins) add_dependencies(${OSGI_UI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_UI_APP}) set_property(TARGET ${OSGI_UI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_UI_APP}.ini) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/berryConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/berryConfig.h" @ONLY) - diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryStarter.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryStarter.cpp index aaf3efd660..edf3f318ee 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryStarter.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryStarter.cpp @@ -1,229 +1,210 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "berryStarter.h" #include "berryPlatform.h" #include "internal/berryInternalPlatform.h" #include #include -//#include #include #include #include #include namespace berry { const QString Starter::XP_APPLICATIONS = "org.blueberry.osgi.applications"; int Starter::Run(int& argc, char** argv, Poco::Util::AbstractConfiguration* config) { // The CTK PluginFramework needs a QCoreApplication if (!qApp) { BERRY_FATAL << "No QCoreApplication instance found. You need to create one prior to calling Starter::Run()"; } InternalPlatform* platform = InternalPlatform::GetInstance(); int returnCode = 0; // startup the internal platform try { platform->Initialize(argc, argv, config); } // the Initialize call can throw exceptions so catch them properly - catch( const berry::PlatformException &e) + catch( const std::exception& e) { BERRY_ERROR << "Caught exception while initializing the Platform : " << e.what(); BERRY_FATAL << "Platform initialization failed. Aborting... \n"; return 1; } platform->Launch(); bool consoleLog = platform->ConsoleLog(); // Add search paths for Qt plugins foreach(QString qtPluginPath, Platform::GetProperty(Platform::PROP_QTPLUGIN_PATH).split(';', QString::SkipEmptyParts)) { if (QFile::exists(qtPluginPath)) { QCoreApplication::addLibraryPath(qtPluginPath); } else if (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 (consoleLog) { std::string pathList; foreach(QString libPath, QCoreApplication::libraryPaths()) { pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString(); } BERRY_INFO << "Qt library search paths: " << pathList; } // run the application IExtensionRegistry* service = platform->GetExtensionRegistry(); if (service == 0) { std::string msg = "The extension point service could not be retrieved. This usually indicates that the org.blueberry.core.runtime plug-in could not be loaded."; platform->GetLogger()->log( Poco::Message( "Starter", msg, Poco::Message::PRIO_FATAL)); BERRY_FATAL << msg; returnCode = 1; } else { QList extensions( service->GetConfigurationElementsFor(Starter::XP_APPLICATIONS)); QList::iterator iter; for (iter = extensions.begin(); iter != extensions.end();) { if ((*iter)->GetName() != "application") iter = extensions.erase(iter); else ++iter; } std::string argApplication = Platform::GetConfiguration().getString( Platform::ARG_APPLICATION.toStdString(), ""); IApplication* app = 0; if (extensions.size() == 0) { BERRY_FATAL << "No extensions configured into extension-point '" << Starter::XP_APPLICATIONS << "' found. Aborting.\n"; returnCode = 0; } else if (extensions.size() == 1) { if (!argApplication.empty()) BERRY_INFO(consoleLog) << "One '" << Starter::XP_APPLICATIONS << "' extension found, ignoring " << Platform::ARG_APPLICATION << " argument.\n"; QList runs( extensions[0]->GetChildren("run")); app = runs.front()->CreateExecutableExtension("class"); - if (app == 0) - { -// // support legacy BlueBerry extensions -// if (IConfigurationElementLegacy* legacyConfigElement = -// dynamic_cast(runs.front().GetPointer())) -// { -// app = legacyConfigElement->CreateExecutableExtension ("class", IApplication::GetManifestName()); -// } - } } else { if (argApplication.empty()) { BERRY_WARN << "You must provide an application id via \"" << Platform::ARG_APPLICATION << "=\""; BERRY_INFO << "Possible application ids are:"; for (iter = extensions.begin(); iter != extensions.end(); ++iter) { QString appid = (*iter)->GetAttribute("id"); if (!appid.isEmpty()) { BERRY_INFO << appid.toStdString(); } } returnCode = 0; } else { for (iter = extensions.begin(); iter != extensions.end(); ++iter) { BERRY_INFO(consoleLog) << "Checking applications extension from: " << (*iter)->GetContributor()->GetName().toStdString() << std::endl; QString appid = (*iter)->GetAttribute("id"); if (!appid.isNull()) { BERRY_INFO(consoleLog) << "Found id: " << appid.toStdString() << std::endl; if (!appid.isEmpty() && appid == QString::fromStdString(argApplication)) { QList runs((*iter)->GetChildren("run")); app = runs.front()->CreateExecutableExtension("class"); -// if (app == 0) -// { -// // try legacy BlueBerry extensions -// if (IConfigurationElementLegacy* legacyConfigElement = -// dynamic_cast(runs.front().GetPointer())) -// { -// app = legacyConfigElement->CreateExecutableExtension ("class", IApplication::GetManifestName()); -// } -// } break; } } else { BERRY_ERROR << "missing attribute: id"; } } } } if (app == 0) { BERRY_ERROR << "Could not create executable application extension for id: " << argApplication << std::endl; returnCode = 1; } else { returnCode = app->Start(); delete app; } } platform->Shutdown(); return returnCode; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h index dc14cf7ea9..9dcd078b9f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h @@ -1,705 +1,705 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPREFERENCES_H_ #define BERRYIPREFERENCES_H_ #include #include "berryObject.h" #include "berryBackingStoreException.h" namespace berry { /** * A node in a hierarchical collection of preference data. * *

* This interface allows applications to store and retrieve user and system * preference data. This data is stored persistently in an * implementation-dependent backing store. Typical implementations include flat * files, OS-specific registries, directory servers and SQL databases. * *

* For each bundle, there is a separate tree of nodes for each user, and one for * system preferences. The precise description of "user" and "system" will vary * from one bundle to another. Typical information stored in the user preference * tree might include font choice, and color choice for a bundle which interacts * with the user via a servlet. Typical information stored in the system * preference tree might include installation data, or things like high score * information for a game program. * *

* Nodes in a preference tree are named in a similar fashion to directories in a * hierarchical file system. Every node in a preference tree has a node name * (which is not necessarily unique), a unique absolute path name , * and a path name relative to each ancestor including itself. * *

* The root node has a node name of the empty QString object (""). * Every other node has an arbitrary node name, specified at the time it is * created. The only restrictions on this name are that it cannot be the empty * string, and it cannot contain the slash character ('/'). * *

* The root node has an absolute path name of "/". Children of the * root node have absolute path names of "/" + <node name> * . All other nodes have absolute path names of <parent's absolute * path name> + "/" + <node name> . Note that * all absolute path names begin with the slash character. * *

* A node n 's path name relative to its ancestor a is simply the * string that must be appended to a 's absolute path name in order to * form n 's absolute path name, with the initial slash character (if * present) removed. Note that: *

    *
  • No relative path names begin with the slash character. *
  • Every node's path name relative to itself is the empty string. *
  • Every node's path name relative to its parent is its node name (except * for the root node, which does not have a parent). *
  • Every node's path name relative to the root is its absolute path name * with the initial slash character removed. *
* *

* Note finally that: *

    *
  • No path name contains multiple consecutive slash characters. *
  • No path name with the exception of the root's absolute path name end in * the slash character. *
  • Any string that conforms to these two rules is a valid path name. *
* *

* Each Preference node has zero or more properties associated with * it, where a property consists of a name and a value. The bundle writer is * free to choose any appropriate names for properties. Their values can be of * type QString,long,int,bool, * std::vector,float, or double but they can * always be accessed as if they were QString objects. * *

* All node name and property name comparisons are case-sensitive. * *

* All of the methods that modify preference data are permitted to operate * asynchronously; they may return immediately, and changes will eventually * propagate to the persistent backing store, with an implementation-dependent * delay. The flush method may be used to synchronously force updates * to the backing store. * *

* Implementations must automatically attempt to flush to the backing store any * pending updates for a bundle's preferences when the bundle is stopped or * otherwise ungets the IPreferences Service. * *

* The methods in this class may be invoked concurrently by multiple threads in * a single Java Virtual Machine (JVM) without the need for external * synchronization, and the results will be equivalent to some serial execution. * If this class is used concurrently by multiple JVMs that store their * preference data in the same backing store, the data store will not be * corrupted, but no other guarantees are made concerning the consistency of the * preference data. * * * @version $Revision$ */ struct org_blueberry_core_runtime_EXPORT IPreferences : virtual public Object { berryObjectMacro(berry::IPreferences) virtual ~IPreferences(); /** * Associates the specified value with the specified key in this node. * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws NullPointerException if key or value is * null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual void Put(const QString& key, const QString& value) = 0; /** * Returns the value associated with the specified key in this * node. Returns the specified default if there is no value associated with * the key, or the backing store is inaccessible. * * @param key key whose associated value is to be returned. * @param def the value to be returned in the event that this node has no * value associated with key or the backing store is * inaccessible. * @return the value associated with key, or def if * no value is associated with key. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if key is null. (A * null default is permitted.) */ virtual QString Get(const QString& key, const QString& def) const = 0; /** * Removes the value associated with the specified key in this * node, if any. * * @param key key whose mapping is to be removed from this node. * @see #get(const QString&,const QString&) * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual void Remove(const QString& key) = 0; /** * Removes all of the properties (key-value associations) in this node. This * call has no effect on any descendants of this node. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #remove(const QString&) */ virtual void Clear() = 0; /** * Associates a QString object representing the specified * int value with the specified key in this node. The * associated string is the one that would be returned if the int * value were passed to Integer.toString(int). This method is * intended for use in conjunction with {@link #getInt}method. * *

* Implementor's note: it is not necessary that the property value * be represented by a QString object in the backing store. If the * backing store supports integer values, it is not unreasonable to use * them. This implementation detail is not visible through the * IPreferences API, which allows the value to be read as an * int (with getInt or a QString (with * get) type. * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getInt(const QString&,int) */ virtual void PutInt(const QString& key, int value) = 0; /** * Returns the int value represented by the QString * object associated with the specified key in this node. The * QString object is converted to an int as by * Integer.parseInt(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Integer.parseInt(QString) would throw a * NumberFormatException if the associated value were * passed. This method is intended for use in conjunction with the * {@link #putInt}method. * * @param key key whose associated value is to be returned as an * int. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as an int or the backing store is * inaccessible. * @return the int value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as an int type. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #putInt(const QString&,int) * @see #get(const QString&,const QString&) */ virtual int GetInt(const QString& key, int def) const = 0; /** * Associates a QString object representing the specified * long value with the specified key in this node. The * associated QString object is the one that would be returned if * the long value were passed to Long.toString(long). * This method is intended for use in conjunction with the {@link #getLong} * method. * *

* Implementor's note: it is not necessary that the value * be represented by a QString type in the backing store. If the * backing store supports long values, it is not unreasonable to * use them. This implementation detail is not visible through the * IPreferences API, which allows the value to be read as a * long (with getLong or a QString (with * get) type. * * @param key key with which the string form of value * is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getLong(const QString&,long) */ virtual void PutLong(const QString& key, long value) = 0; /** * Returns the long value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a long as by * Long.parseLong(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Long.parseLong(QString) would throw a * NumberFormatException if the associated value were * passed. This method is intended for use in conjunction with the * {@link #putLong}method. * * @param key key whose associated value is to be returned as a * long value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a long type or the backing * store is inaccessible. * @return the long value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a long type. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #putLong(const QString&,long) * @see #get(const QString&,const QString&) */ virtual long GetLong(const QString& key, long def) const = 0; /** * Associates a QString object representing the specified * bool value with the specified key in this node. The * associated string is "true" if the value is true, and "false" * if it is false. This method is intended for use in * conjunction with the {@link #getBool}method. * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports bool values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a bool * (with getBool) or a QString (with get) * type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getBool(const QString&,bool) * @see #get(const QString&,const QString&) */ virtual void PutBool(const QString& key, bool value) = 0; /** * Returns the bool value represented by the QString * object associated with the specified key in this node. Valid * strings are "true", which represents true, and "false", which * represents false. Case is ignored, so, for example, "TRUE" * and "False" are also valid. This method is intended for use in * conjunction with the {@link #putBool}method. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated * value is something other than "true" or "false", ignoring case. * * @param key key whose associated value is to be returned as a * bool. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a bool or the backing store * is inaccessible. * @return the bool value represented by the std::string * object associated with key in this node, or * null if the associated value does not exist or cannot * be interpreted as a bool. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #get(const QString&,const QString&) * @see #putBool(const QString&,bool) */ virtual bool GetBool(const QString& key, bool def) const = 0; /** * Associates a QString object representing the specified * float value with the specified key in this node. * The associated QString object is the one that would be returned * if the float value were passed to * Float.toString(float). This method is intended for use in * conjunction with the {@link #getFloat}method. * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports float values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a float (with * getFloat) or a QString (with get) type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getFloat(const QString&,float) */ virtual void PutFloat(const QString& key, float value) = 0; /** * Returns the float value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a float value as by * Float.parseFloat(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Float.parseFloat(QString) would throw a * NumberFormatException if the associated value were passed. * This method is intended for use in conjunction with the {@link #putFloat} * method. * * @param key key whose associated value is to be returned as a * float value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a float type or the backing * store is inaccessible. * @return the float value represented by the string associated * with key in this node, or def if the * associated value does not exist or cannot be interpreted as a * float type. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if key is null. * @see #putFloat(const QString&,float) * @see #get(const QString&,const QString&) */ virtual float GetFloat(const QString& key, float def) const = 0; /** * Associates a QString object representing the specified * double value with the specified key in this node. * The associated QString object is the one that would be returned * if the double value were passed to * Double.toString(double). This method is intended for use in * conjunction with the {@link #getDouble}method * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports double values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a double (with * getDouble) or a QString (with get) * type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getDouble(const QString&,double) */ virtual void PutDouble(const QString& key, double value) = 0; /** * Returns the double value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a double value as by * Double.parseDouble(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Double.parseDouble(QString) would throw * a NumberFormatException if the associated value were passed. * This method is intended for use in conjunction with the * {@link #putDouble}method. * * @param key key whose associated value is to be returned as a * double value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a double type or the backing * store is inaccessible. * @return the double value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a double type. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the the {@link #removeNode()}method. * @throws NullPointerException if key is null. * @see #putDouble(const QString&,double) * @see #get(const QString&,const QString&) */ virtual double GetDouble(const QString& key, double def) const = 0; /** * Associates a QByteArray object representing the specified * QByteArray with the specified key in this node. The * associated QByteArray object is stored in Base64 encoding. * This method is intended for use in conjunction with the * {@link #getByteArray}method. * * @param key key with which the string form of value * is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key or value is * null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #GetByteArray(const QString&,const QByteArray&) * @see #Get(const QString&,const QString&) */ virtual void PutByteArray(const QString& key, const QByteArray& value) = 0; /** - * Returns the std::vector value represented by the QString + * Returns the QByteArray value represented by the QString * object associated with the specified key in this node. Valid * QString objects are Base64 encoded binary data, as * defined in RFC 2045 , * Section 6.8, with one minor change: the string must consist solely of * characters from the Base64 Alphabet ; no newline characters or * extraneous characters are permitted. This method is intended for use in * conjunction with the {@link #putByteArray}method. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated * value is not a valid Base64 encoded byte array (as defined above). * * @param key key whose associated value is to be returned as a * std::vector object. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a std::vector type, or the backing * store is inaccessible. * @return the std::vector value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a std::vector. * @throws NullPointerException if key is null. (A * null value for def is permitted.) * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #get(const QString&,const QString&) * @see #putByteArray(const QString&,std::vector) */ virtual QByteArray GetByteArray(const QString& key, const QByteArray& def) const = 0; /** * Returns all of the keys that have an associated value in this node. (The * returned array will be of size zero if this node has no preferences and * not null!) * * @return an array of the keys that have an associated value in this node. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual QStringList Keys() const = 0; /** * Returns the names of the children of this node. (The returned array will * be of size zero if this node has no children and not null!) * * @return the names of the children of this node. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual QStringList ChildrenNames() const = 0; /** * Returns the parent of this node, or null if this is the root. * * @return the parent of this node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual IPreferences::Pointer Parent() const = 0; /** * Returns a named IPreferences object (node), creating it and any * of its ancestors if they do not already exist. Accepts a relative or * absolute pathname. Absolute pathnames (which begin with '/') * are interpreted relative to the root of this node. Relative pathnames * (which begin with any character other than '/') are * interpreted relative to this node itself. The empty string ("") * is a valid relative pathname, referring to this node itself. * *

* If the returned node did not exist prior to this call, this node and any * ancestors that were created by this call are not guaranteed to become * persistent until the flush method is called on the returned * node (or one of its descendants). * * @param pathName the path name of the IPreferences object to * return. * @return the specified IPreferences object. * @throws IllegalArgumentException if the path name is invalid. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if path name is null. * @see #flush() */ virtual IPreferences::Pointer Node(const QString& pathName) = 0; /** * Returns true if the named node exists. Accepts a relative or absolute * pathname. Absolute pathnames (which begin with '/') are * interpreted relative to the root of this node. Relative pathnames (which * begin with any character other than '/') are interpreted * relative to this node itself. The pathname "" is valid, and * refers to this node itself. * *

* If this node (or an ancestor) has already been removed with the * {@link #removeNode()}method, it is legal to invoke this method, * but only with the pathname ""; the invocation will return * false. Thus, the idiom p.nodeExists("") may be * used to test whether p has been removed. * * @param pathName the path name of the node whose existence is to be * checked. * @return true if the specified node exists. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method and * pathname is not the empty string (""). * @throws IllegalArgumentException if the path name is invalid (i.e., it * contains multiple consecutive slash characters, or ends with a * slash character and is more than one character long). */ virtual bool NodeExists(const QString& pathName) const = 0; /** * Removes this node and all of its descendants, invalidating any properties * contained in the removed nodes. Once a node has been removed, attempting * any method other than name(),absolutePath() or * nodeExists("") on the corresponding IPreferences * instance will fail with an IllegalStateException. (The * methods defined on Object can still be invoked on a node after * it has been removed; they will not throw IllegalStateException.) * *

* The removal is not guaranteed to be persistent until the flush * method is called on the parent of this node. * * @throws IllegalStateException if this node (or an ancestor) has already * been removed with the {@link #removeNode()}method. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @see #flush() */ virtual void RemoveNode() throw(Poco::Exception, BackingStoreException) = 0; /** * Returns this node's name, relative to its parent. * * @return this node's name, relative to its parent. */ virtual QString Name() const = 0; /** * Returns this node's absolute path name. Note that: *

    *
  • Root node - The path name of the root node is "/". *
  • Slash at end - Path names other than that of the root node may not * end in slash ('/'). *
  • Unusual names -"." and ".." have no * special significance in path names. *
  • Illegal names - The only illegal path names are those that contain * multiple consecutive slashes, or that end in slash and are not the root. *
* * @return this node's absolute path name. */ virtual QString AbsolutePath() const = 0; /** * Forces any changes in the contents of this node and its descendants to * the persistent store. * *

* Once this method returns successfully, it is safe to assume that all * changes made in the subtree rooted at this node prior to the method * invocation have become permanent. * *

* Implementations are free to flush changes into the persistent store at * any time. They do not need to wait for this method to be called. * *

* When a flush occurs on a newly created node, it is made persistent, as * are any ancestors (and descendants) that have yet to be made persistent. * Note however that any properties value changes in ancestors are not * guaranteed to be made persistent. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #sync() */ virtual void Flush() = 0; /** * Ensures that future reads from this node and its descendants reflect any * changes that were committed to the persistent store (from any VM) prior * to the sync invocation. As a side-effect, forces any changes * in the contents of this node and its descendants to the persistent store, * as if the flush method had been invoked on this node. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #flush() */ virtual void Sync() = 0; }; } // namespace berry #endif /*BERRYIPREFERENCES_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h index d1b6d06d7c..2dc5b376ea 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h @@ -1,73 +1,41 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __BERRY_MACROS_H__ #define __BERRY_MACROS_H__ #include "berryWeakPointer.h" #include "berryExtensionType.h" #define berryObjectMacro(className) \ typedef className Self; \ typedef berry::SmartPointer Pointer; \ typedef berry::SmartPointer ConstPointer; \ typedef berry::WeakPointer WeakPtr; \ typedef berry::WeakPointer ConstWeakPtr; \ static const char* GetStaticClassName() \ { return #className; } - -/* -#define berryNewMacro(x) \ -static Pointer New(void) \ -{ \ - Pointer smartPtr(new x); \ - return smartPtr; \ -} \ - -#define berryNewMacro1Param(x, type1) \ -static Pointer New(type1 param1) \ -{ \ - Pointer smartPtr(new x(param1)); \ - return smartPtr; \ -} \ - -#define berryNewMacro2Param(x, type1, type2) \ -static Pointer New(type1 param1, type2 param2) \ -{ \ - Pointer smartPtr(new x(param1, param2)); \ - return smartPtr; \ -} \ - -#define berryNewMacro3Param(x, type1, type2, type3) \ -static Pointer New(type1 param1, type2 param2, type3 param3) \ -{ \ - Pointer smartPtr (new x(param1, param2, param3)); \ - return smartPtr; \ -} -*/ - - #define BERRY_REGISTER_EXTENSION_CLASS(_ClassType, _PluginContext)\ {\ QString typeName = _PluginContext->getPlugin()->getSymbolicName();\ typeName = (typeName + "_") + _ClassType::staticMetaObject.className();\ ::berry::registerExtensionType<_ClassType>(typeName.toLatin1().data());\ } #endif /*__BERRY_MACROS_H__*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp index 1e4f10f13a..751969f15f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp @@ -1,597 +1,597 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryInternalPlatform.h" #include "berryLog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "berryPlatform.h" #include "berryPlatformException.h" #include "berryDebugUtil.h" //#include "event/berryPlatformEvents.h" //#include "berryPlatformLogChannel.h" #include "berryProvisioningInfo.h" #include "berryCTKPluginActivator.h" #include "berryLogImpl.h" #include #include #include #include #include namespace berry { Poco::Mutex InternalPlatform::m_Mutex; InternalPlatform::InternalPlatform() : m_Initialized(false) , m_Running(false) , m_ConsoleLog(false) , m_PlatformLogger(0) , m_ctkPluginFrameworkFactory(0) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { Poco::Mutex::ScopedLock lock(m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } ctkPluginContext* InternalPlatform::GetCTKPluginFrameworkContext() const { if (m_ctkPluginFrameworkFactory) { return m_ctkPluginFrameworkFactory->getFramework()->getPluginContext(); } return 0; } IAdapterManager* InternalPlatform::GetAdapterManager() const { AssertInitialized(); return NULL; } void InternalPlatform::Initialize(int& argc, char** argv, Poco::Util::AbstractConfiguration* config) { // initialization Poco::Mutex::ScopedLock lock(m_Mutex); m_Argc = &argc; m_Argv = argv; try { this->init(argc, argv); } catch (const Poco::Util::UnknownOptionException& e) { BERRY_WARN << e.displayText(); } this->loadConfiguration(); if (config) { this->config().add(config, 50, false); } m_ConsoleLog = this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG.toStdString()); m_ConfigPath.setPath(QString::fromStdString(this->GetConfiguration().getString("application.configDir"))); m_InstancePath.setPath(QString::fromStdString(this->GetConfiguration().getString("application.dir"))); try { m_InstallPath.setPath(QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_HOME.toStdString()))); } catch (Poco::NotFoundException& ) { m_InstallPath = m_InstancePath; } if (this->GetConfiguration().hasProperty(Platform::ARG_STORAGE_DIR.toStdString())) { QString dataLocation = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_STORAGE_DIR.toStdString(), "")); 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. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '_'; #else QString dataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + '_'; #endif 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); } // Initialize the CTK Plugin Framework ctkProperties fwProps; fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE, userFile.absoluteFilePath()); if (this->GetConfiguration().hasProperty(Platform::ARG_CLEAN.toStdString())) { fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN, ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); } if (this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG.toStdString())) { fwProps.insert("org.commontk.pluginfw.debug.framework", true); fwProps.insert("org.commontk.pluginfw.debug.errors", true); fwProps.insert("org.commontk.pluginfw.debug.pluginfw", true); fwProps.insert("org.commontk.pluginfw.debug.lazy_activation", true); fwProps.insert("org.commontk.pluginfw.debug.resolve", true); } if (this->GetConfiguration().hasProperty(Platform::ARG_PRELOAD_LIBRARY.toStdString())) { QString preloadLibs = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_PRELOAD_LIBRARY.toStdString())); fwProps.insert(ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES, preloadLibs.split(',', QString::SkipEmptyParts)); } m_ctkPluginFrameworkFactory = new ctkPluginFrameworkFactory(fwProps); QSharedPointer pfw = m_ctkPluginFrameworkFactory->getFramework(); pfw->init(); ctkPluginContext* pfwContext = pfw->getPluginContext(); // FIXME: This is a quick-fix for Bug 16224 - Umlaut and other special characters in install/binary path // Assumption : linux provides utf8, windows provides ascii encoded argv lists #ifdef Q_OS_WIN QString provisioningFile = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_PROVISIONING.toStdString())); #else - QString provisioningFile = QString::fromUtf8(this->GetConfiguration().getString(Platform::ARG_PROVISIONING.toStdString())); + QString provisioningFile = QString::fromUtf8(this->GetConfiguration().getString(Platform::ARG_PROVISIONING.toStdString()).c_str()); #endif if (!provisioningFile.isEmpty()) { BERRY_INFO(m_ConsoleLog) << "Using provisioning file: " << provisioningFile; ProvisioningInfo provInfo(provisioningFile); // it can still happen, that the encoding is not compatible with the fromUtf8 function ( i.e. when manipulating the LANG variable // in such case, the QStringList in provInfo is empty which we can easily check for if( provInfo.getPluginDirs().empty() ) { BERRY_ERROR << "Cannot search for provisioning file, the retrieved directory list is empty.\n" << "This can occur if there are some special (non-ascii) characters in the install path."; throw berry::PlatformException("No provisioning file specified. Terminating..."); } foreach(QString pluginPath, provInfo.getPluginDirs()) { ctkPluginFrameworkLauncher::addSearchPath(pluginPath); } bool forcePluginOverwrite = this->GetConfiguration().hasOption(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString()); QList pluginsToStart = provInfo.getPluginsToStart(); foreach(QUrl pluginUrl, provInfo.getPluginsToInstall()) { if (forcePluginOverwrite) { uninstallPugin(pluginUrl, pfwContext); } try { BERRY_INFO(m_ConsoleLog) << "Installing CTK plug-in from: " << pluginUrl.toString().toStdString(); QSharedPointer plugin = pfwContext->installPlugin(pluginUrl); if (pluginsToStart.contains(pluginUrl)) { m_CTKPluginsToStart << plugin->getPluginId(); } } catch (const ctkPluginException& e) { QString errorMsg; QDebug dbg(&errorMsg); dbg << e.printStackTrace(); BERRY_ERROR << qPrintable(errorMsg); } } } else { BERRY_INFO << "No provisioning file set."; } 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()); m_PlatformLogger = &Poco::Logger::create("PlatformLogger", m_PlatformLogChannel, Poco::Message::PRIO_TRACE); m_Initialized = true; #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(m_UserPath); #endif } void InternalPlatform::uninstallPugin(const QUrl& pluginUrl, ctkPluginContext* pfwContext) { QFileInfo libInfo(pluginUrl.toLocalFile()); QString libName = libInfo.baseName(); if (libName.startsWith("lib")) { libName = libName.mid(3); } QString symbolicName = libName.replace('_', '.'); foreach(QSharedPointer plugin, pfwContext->getPlugins()) { if (plugin->getSymbolicName() == symbolicName && plugin->getLocation() != pluginUrl.toString()) { BERRY_WARN << "A plug-in with the symbolic name " << symbolicName.toStdString() << " but different location is already installed. Trying to uninstall " << plugin->getLocation().toStdString(); plugin->uninstall(); return; } } } void InternalPlatform::Launch() { AssertInitialized(); if (m_Running) return; m_Running = true; this->run(); } void InternalPlatform::Shutdown() { QSharedPointer ctkPluginFW; { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); DebugUtil::SaveState(m_UserPath); ctkPluginFW = m_ctkPluginFrameworkFactory->getFramework(); m_Initialized = false; } ctkPluginFW->stop(); this->uninitialize(); // wait 10 seconds for the CTK plugin framework to stop ctkPluginFW->waitForStop(10000); } void InternalPlatform::AssertInitialized() const { if (!m_Initialized) throw Poco::SystemException("The Platform has not been initialized yet!"); } IExtensionRegistry* InternalPlatform::GetExtensionRegistry() { if (m_RegistryTracker.isNull()) { m_RegistryTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); m_RegistryTracker->open(); } return m_RegistryTracker->getService(); } IPreferencesService *InternalPlatform::GetPreferencesService() { if (m_PreferencesTracker.isNull()) { m_PreferencesTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); m_PreferencesTracker->open(); } return m_PreferencesTracker->getService(); } QDir InternalPlatform::GetConfigurationPath() { return m_ConfigPath; } QDir InternalPlatform::GetInstallPath() { return m_InstallPath; } QDir InternalPlatform::GetInstancePath() { return m_InstancePath; } bool InternalPlatform::GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create) { QFileInfo tmpStatePath(m_BaseStatePath.absoluteFilePath(plugin->getSymbolicName())); if (tmpStatePath.exists()) { if (tmpStatePath.isDir() && tmpStatePath.isWritable() && tmpStatePath.isReadable()) { statePath.setPath(tmpStatePath.absoluteFilePath()); return true; } else { return false; } } else if (create) { bool created = statePath.mkpath(tmpStatePath.absoluteFilePath()); if (created) { statePath.setPath(tmpStatePath.absoluteFilePath()); return true; } return false; } return false; } //PlatformEvents& InternalPlatform::GetEvents() //{ // return m_Events; //} QDir InternalPlatform::GetUserPath() { return m_UserPath; } ILog *InternalPlatform::GetLog(const QSharedPointer &plugin) const { LogImpl* result = m_Logs.value(plugin->getPluginId()); if (result != NULL) 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 { Poco::Mutex::ScopedLock lock(m_Mutex); return (m_Initialized && m_Running); } QSharedPointer InternalPlatform::GetPlugin(const QString &symbolicName) { QList > plugins = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->getPlugins(); QSharedPointer res(0); 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 = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->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()); return reversePlugins; } Poco::Logger* InternalPlatform::GetLogger() { return m_PlatformLogger; } Poco::Util::LayeredConfiguration& InternalPlatform::GetConfiguration() const { return this->config(); } QStringList InternalPlatform::GetApplicationArgs() const { return m_FilteredArgs; } int& InternalPlatform::GetRawApplicationArgs(char**& argv) { argv = m_Argv; return *m_Argc; } void InternalPlatform::defineOptions(Poco::Util::OptionSet& options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &InternalPlatform::PrintHelp)); options.addOption(helpOption); Poco::Util::Option newInstanceOption(Platform::ARG_NEWINSTANCE.toStdString(), "", "forces a new instance of this application"); newInstanceOption.binding(Platform::ARG_NEWINSTANCE.toStdString()); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(Platform::ARG_CLEAN.toStdString(), "", "cleans the plugin cache"); cleanOption.binding(Platform::ARG_CLEAN.toStdString()); options.addOption(cleanOption); Poco::Util::Option appOption(Platform::ARG_APPLICATION.toStdString(), "", "the id of the application extension to be executed"); appOption.argument("").binding(Platform::ARG_APPLICATION.toStdString()); options.addOption(appOption); Poco::Util::Option storageDirOption(Platform::ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data"); storageDirOption.argument("

").binding(Platform::ARG_STORAGE_DIR.toStdString()); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(Platform::ARG_CONSOLELOG.toStdString(), "", "log messages to the console"); consoleLogOption.binding(Platform::ARG_CONSOLELOG.toStdString()); options.addOption(consoleLogOption); Poco::Util::Option forcePluginOption(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString(), "", "force installing plug-ins with same symbolic name"); forcePluginOption.binding(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString()); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(Platform::ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library"); preloadLibsOption.argument("").repeatable(true).callback(Poco::Util::OptionCallback(this, &InternalPlatform::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); Poco::Util::Option testPluginOption(Platform::ARG_TESTPLUGIN.toStdString(), "", "the plug-in to be tested"); testPluginOption.argument("").binding(Platform::ARG_TESTPLUGIN.toStdString()); options.addOption(testPluginOption); Poco::Util::Option testAppOption(Platform::ARG_TESTAPPLICATION.toStdString(), "", "the application to be tested"); testAppOption.argument("").binding(Platform::ARG_TESTAPPLICATION.toStdString()); options.addOption(testAppOption); Poco::Util::Option noRegistryCacheOption(Platform::ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry"); noRegistryCacheOption.binding(Platform::ARG_NO_REGISTRY_CACHE.toStdString()); options.addOption(noRegistryCacheOption); Poco::Util::Option noLazyRegistryCacheLoadingOption(Platform::ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString(), "", "do not use lazy cache loading for the registry"); noLazyRegistryCacheLoadingOption.binding(Platform::ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString()); options.addOption(noLazyRegistryCacheLoadingOption); Poco::Util::Option registryMultiLanguageOption(Platform::ARG_REGISTRY_MULTI_LANGUAGE.toStdString(), "", "enable multi-language support for the registry"); registryMultiLanguageOption.binding(Platform::ARG_REGISTRY_MULTI_LANGUAGE.toStdString()); options.addOption(registryMultiLanguageOption); Poco::Util::Option xargsOption(Platform::ARG_XARGS.toStdString(), "", "Extended argument list"); xargsOption.argument("").binding(Platform::ARG_XARGS.toStdString()); options.addOption(xargsOption); Poco::Util::Application::defineOptions(options); } void InternalPlatform::handlePreloadLibraryOption(const std::string& /*name*/, const std::string& value) { std::string oldVal; if (this->config().hasProperty(Platform::ARG_PRELOAD_LIBRARY.toStdString())) { oldVal = this->config().getString(Platform::ARG_PRELOAD_LIBRARY.toStdString()); } this->config().setString(Platform::ARG_PRELOAD_LIBRARY.toStdString(), oldVal + "," + value); } int InternalPlatform::main(const std::vector& args) { for(std::vector::const_iterator i = args.begin(); i != args.end(); ++i) { m_FilteredArgs << QString::fromStdString(*i); } //m_FilteredArgs.insert(m_FilteredArgs.begin(), this->config().getString("application.argv[0]")); ctkPluginContext* context = GetCTKPluginFrameworkContext(); QFileInfo storageDir = context->getDataFile(""); m_ctkPluginFrameworkFactory->getFramework()->start(); foreach(long pluginId, m_CTKPluginsToStart) { BERRY_INFO(m_ConsoleLog) << "Starting CTK plug-in: " << context->getPlugin(pluginId)->getSymbolicName().toStdString() << " [" << pluginId << "]"; // do not change the autostart setting of this plugin context->getPlugin(pluginId)->start(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); } return EXIT_OK; } void InternalPlatform::PrintHelp(const std::string&, const std::string&) { Poco::Util::HelpFormatter help(this->options()); help.setAutoIndent(); help.setCommand(this->commandName()); help.format(std::cout); exit(EXIT_OK); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp index 07adce79c0..49865b120f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp @@ -1,495 +1,505 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPreferences.h" #include "berryAbstractPreferencesStorage.h" #include #include namespace berry { Preferences::Preferences(const PropertyMap& _Properties , const QString& _Name , Preferences* _Parent , AbstractPreferencesStorage* _Storage) : m_Properties(_Properties) , m_Path(_Parent ? _Parent->AbsolutePath() + (_Parent->AbsolutePath() == "/" ? "": "/") + _Name : "/") , m_Name(_Name) , m_Parent(_Parent) , m_Root(_Parent ? _Parent->m_Root : this) , m_Removed(false) , m_Storage(_Storage) { // root node if parent is 0 if (_Parent != 0) { // save as child in parent _Parent->m_Children.push_back(Preferences::Pointer(this)); } } bool Preferences::Has(const QString& key ) const { QMutexLocker scopedMutex(&m_Mutex); return this->Has_unlocked(key); } bool Preferences::Has_unlocked(const QString& key ) const { return (m_Properties.find(key) != m_Properties.end()); } bool Preferences::IsDirty() const { QMutexLocker scopedMutex(&m_Mutex); bool dirty = m_Dirty; for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { // break condition: if one node is dirty the whole tree is dirty if(dirty) break; else dirty = (*it)->IsDirty(); } return dirty; } QString Preferences::ToString() const { return QString("Preferences[") + m_Path + "]"; } bool Preferences::Equals(const Preferences* rhs) const { if(rhs == 0) return false; return (this->m_Path == rhs->m_Path); } Preferences::PropertyMap Preferences::GetProperties() const { QMutexLocker scopedMutex(&m_Mutex); return m_Properties; } Preferences::ChildrenList Preferences::GetChildren() const { QMutexLocker scopedMutex(&m_Mutex); return m_Children; } QString Preferences::AbsolutePath() const { return m_Path; } QStringList Preferences::ChildrenNames() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); QStringList names; for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { names.push_back((*it)->Name()); } return names; } AbstractPreferencesStorage* Preferences::GetStorage() const { return m_Storage; } void Preferences::Clear() { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); - m_Properties.clear(); - this->SetDirty_unlocked(true); + { + QMutexLocker scopedMutex(&m_Mutex); + AssertValid_unlocked(); + m_Properties.clear(); + } + this->SetDirty(true); } void Preferences::Flush() { m_Storage->Flush(this); // if something is written, make the tree undirty // there is a race condition here: after flushing, another thread // could modify this object before we can set dirty to false, // but we cannot hold a lock before flushing because the operation // will call other methods on this object, which would lead // to a recursive lock. this->SetDirty(false); } QString Preferences::Get(const QString& key, const QString& def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key] : def; } bool Preferences::GetBool(const QString& key, bool def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? (m_Properties[key] == "true" ? true: false) : def; } QByteArray Preferences::GetByteArray(const QString& key, const QByteArray& def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? QByteArray::fromBase64(m_Properties[key].toLatin1()) : def; } double Preferences::GetDouble(const QString& key, double def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toDouble() : def; } float Preferences::GetFloat(const QString& key, float def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toFloat() : def; } int Preferences::GetInt(const QString& key, int def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toInt() : def; } long Preferences::GetLong(const QString& key, long def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toLong() : def; } QStringList Preferences::Keys() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return m_Properties.keys(); } QString Preferences::Name() const { return m_Name; } IPreferences::Pointer Preferences::Node(const QString& path) { QMutexLocker scopedMutex(&m_Mutex); return this->Node_unlocked(path); } Preferences::Pointer Preferences::Node_unlocked(const QString& path) { QString pathName = path; AssertValid_unlocked(); AssertPath_unlocked(pathName); Preferences::Pointer node; // self reference if(pathName == "") return Preferences::Pointer(this); // absolute path else if(pathName[0] == '/') { pathName = pathName.mid(1); // call root with this relative path if (this == m_Root) return m_Root->Node_unlocked(pathName); else return m_Root->Node(pathName).Cast(); } // relative path else { // check if pathName contains anymore names QString name = pathName; // create new child nodes as long as there are names in the path int pos = pathName.indexOf('/'); // cut from the beginning if(pos != -1) { name = pathName.left(pos); pathName = pathName.mid(pos+1); } // now check if node exists->if not: make new for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); it++) { // node found if((*it)->Name() == name && (*it)->IsRemoved() == false) { node = *it; break; } } // node not found create new one if(node.IsNull()) { // the new node automatically pushes itself into the children array of *this* Preferences::Pointer newNode(new Preferences(PropertyMap(), name, this, m_Storage)); node = newNode.GetPointer(); // this branch is dirty now -> prefs must be rewritten persistently this->SetDirty_unlocked(true); } // call Node() again if there are any names left on the path if(pos != -1) { if (this == node.GetPointer()) node = node->Node_unlocked(pathName); else node = node->Node(pathName).Cast(); } } return node; } bool Preferences::NodeExists(const QString& path) const { QString pathName = path; QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); AssertPath_unlocked(pathName); bool nodeExists = false; // absolute path if(pathName[0] == '/') { pathName = pathName.mid(1); // call root with this relative path return m_Root->NodeExists(pathName); } // relative path else { // check if pathName contains anymore names QString name = pathName; // create new child nodes as long as there are names in the path int pos = pathName.indexOf("/"); // cut from the beginning if(pos != -1) { name = pathName.left(pos); pathName = pathName.mid(pos+1); } // now check if node exists->if not: make new for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); it++) { // node found if((*it)->Name() == name) { // call recursively if more names on the path exist if(pos != -1) nodeExists = (*it)->NodeExists(pathName); else nodeExists = true; break; } } } return nodeExists; } void Preferences::Put(const QString& key, const QString& value) { - QMutexLocker scopedMutex(&m_Mutex); - AssertValid_unlocked(); + { + QMutexLocker scopedMutex(&m_Mutex); + AssertValid_unlocked(); - m_Properties[key] = value; - this->SetDirty_unlocked(true); + m_Properties[key] = value; + } + this->SetDirty(true); } void Preferences::PutByteArray(const QString& key, const QByteArray& value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, value.toBase64().data()); } void Preferences::PutBool(const QString& key, bool value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, value ? "true" : "false"); } void Preferences::PutDouble(const QString& key, double value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, QString::number(value)); } void Preferences::PutFloat(const QString& key, float value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, QString::number(value)); } void Preferences::PutInt(const QString& key, int value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, QString::number(value)); } void Preferences::PutLong(const QString& key, long value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, QString::number(value)); } void Preferences::Remove(const QString& key) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); PropertyMap::iterator it = m_Properties.find(key); if(it != m_Properties.end()) m_Properties.erase(it); } void Preferences::RemoveNode() throw(Poco::Exception, BackingStoreException) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->SetRemoved_unlocked(true); m_Parent->m_Children.erase(std::find(m_Parent->m_Children.begin(), m_Parent->m_Children.end(), Preferences::Pointer(this))); } void Preferences::Sync() throw(Poco::Exception, BackingStoreException) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Flush(); } void Preferences::AssertValid_unlocked() const { if(m_Removed) { throw ctkIllegalStateException(QString("no node at '") + m_Path + "'"); } } void Preferences::AssertPath_unlocked(const QString& pathName) { if(pathName.indexOf("//") != -1) { throw ctkInvalidArgumentException(QString("Illegal // in m_Path m_Name '") + pathName + "'"); } int strLength = pathName.size(); if(strLength > 1 && pathName[strLength-1] == '/') { throw ctkInvalidArgumentException(QString("Trailing / in m_Path m_Name '") + pathName + "'"); } } IPreferences::Pointer Preferences::Parent() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return IPreferences::Pointer(m_Parent); } void Preferences::SetDirty( bool _Dirty ) { - QMutexLocker scopedMutex(&m_Mutex); - this->SetDirty_unlocked(_Dirty); + { + QMutexLocker scopedMutex(&m_Mutex); + m_Dirty = _Dirty; + } + if(_Dirty) + { + this->OnChanged.Send(this); + } } void Preferences::SetDirty_unlocked( bool _Dirty ) { m_Dirty = _Dirty; if(_Dirty) this->OnChanged.Send(this); /* for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { (*it)->SetDirty(_Dirty); } */ } void Preferences::SetRemoved( bool _Removed ) { QMutexLocker scopedMutex(&m_Mutex); this->SetRemoved_unlocked(_Removed); } void Preferences::SetRemoved_unlocked( bool _Removed ) { m_Removed = _Removed; for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { (*it)->SetRemoved(_Removed); } } /* Preferences::ChildrenList& Preferences::GetChildren() const { return m_Children; }*/ bool Preferences::IsRemoved() const { QMutexLocker scopedMutex(&m_Mutex); return m_Removed; } Preferences::~Preferences() { } } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.cpp b/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.cpp index c15a053b6d..149a331d4a 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.cpp @@ -1,94 +1,95 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryBlueBerryTestDriver.h" #include "internal/berryTestRegistry.h" #include "cppunit/TestRunner.h" #include "cppunit/TestResult.h" #include "cppunit/TestResultCollector.h" namespace berry { -BlueBerryTestDriver::BlueBerryTestDriver(const std::vector< - ITestDescriptor::Pointer>& descriptors, +BlueBerryTestDriver::BlueBerryTestDriver( + const QList& descriptors, bool uitests, - const std::string& testName, - bool wait) : - descriptors(descriptors), uitests(uitests), testName(testName), wait(wait) + const QString& testName, + bool wait) + : descriptors(descriptors) + , uitests(uitests) + , testName(testName) + , wait(wait) { } int BlueBerryTestDriver::Run() { CppUnit::TestRunner runner; unsigned int testCounter = 0; - for (std::vector::iterator i = descriptors.begin(); i - != descriptors.end(); ++i) + foreach (const ITestDescriptor::Pointer& descr, descriptors) { - ITestDescriptor::Pointer descr(*i); if (descr->IsUITest() == uitests) { CppUnit::Test* test = descr->CreateTest(); runner.addTest(test); ++testCounter; } } if (testCounter == 0) { std::cout << "No " << (uitests ? "UI " : "") << "tests registered." << std::endl; return 0; } /* std::vector args; args.push_back("BlueBerryTestDriver"); if (testName.empty()) args.push_back("-all"); else args.push_back(testName); if (wait) args.push_back("-wait"); return runner.run(args) ? 0 : 1; */ CppUnit::TestResult controller; CppUnit::TestResultCollector result; controller.addListener(&result); runner.run(controller); return result.wasSuccessful() ? 0 : 1; } -int BlueBerryTestDriver::Run(const std::string& pluginId, bool uitests) +int BlueBerryTestDriver::Run(const QString& pluginId, bool uitests) { TestRegistry testRegistry; - const std::vector& tests = testRegistry.GetTestsForId( + const QList& tests = testRegistry.GetTestsForId( pluginId); BlueBerryTestDriver driver(tests, uitests); return driver.Run(); } } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.h b/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.h index 436ee33856..2336f659c8 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/berryBlueBerryTestDriver.h @@ -1,55 +1,53 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYBLUEBERRYTESTDRIVER_H_ #define BERRYBLUEBERRYTESTDRIVER_H_ #include #include "berryITestDescriptor.h" -#include - namespace berry { /** * A TestDriver for CppUnit that supports running tests inside BlueBerry as well as * running standalone. * Example call: TODO */ class BERRY_TEST_EXPORT BlueBerryTestDriver { public: - BlueBerryTestDriver(const std::vector& descriptors, bool uitests = false, const std::string& testName="", bool wait=false); + BlueBerryTestDriver(const QList& descriptors, bool uitests = false, const QString& testName="", bool wait=false); int Run(); - static int Run(const std::string& pluginId, bool uitests = false); + static int Run(const QString& pluginId, bool uitests = false); protected: - std::vector descriptors; + QList descriptors; bool uitests; - std::string testName; + QString testName; bool wait; }; } #endif /* BERRYBLUEBERRYTESTDRIVER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/berryCoreTestApplication.cpp b/BlueBerry/Bundles/org.blueberry.test/src/berryCoreTestApplication.cpp index bb716a712b..b7bd360175 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/berryCoreTestApplication.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/berryCoreTestApplication.cpp @@ -1,54 +1,55 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCoreTestApplication.h" #include #include #include "berryBlueBerryTestDriver.h" namespace berry { CoreTestApplication::CoreTestApplication() { } CoreTestApplication::CoreTestApplication(const CoreTestApplication& other) + : QObject() { Q_UNUSED(other) } int CoreTestApplication::Start() { std::string testPlugin; try { - testPlugin = Platform::GetConfiguration().getString(Platform::ARG_TESTPLUGIN); + testPlugin = Platform::GetConfiguration().getString(Platform::ARG_TESTPLUGIN.toStdString()); } catch (const Poco::NotFoundException& /*e*/) { BERRY_ERROR << "You must specify a test plug-in id via " << Platform::ARG_TESTPLUGIN << "="; return 1; } - return BlueBerryTestDriver::Run(testPlugin); + return BlueBerryTestDriver::Run(QString::fromStdString(testPlugin)); } void CoreTestApplication::Stop() { } } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h b/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h index 67540cc46e..84b03d5239 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h @@ -1,42 +1,42 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYITESTDESCRIPTOR_H_ #define BERRYITESTDESCRIPTOR_H_ #include #include #include namespace berry { struct ITestDescriptor : public Object { berryObjectMacro(berry::ITestDescriptor) virtual CppUnit::Test* CreateTest() = 0; - virtual std::string GetId() const = 0; - virtual std::string GetContributor() const = 0; - virtual std::string GetDescription() const = 0; + virtual QString GetId() const = 0; + virtual QString GetContributor() const = 0; + virtual QString GetDescription() const = 0; virtual bool IsUITest() const = 0; }; } #endif /* BERRYITESTDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp index fc3b966cae..a4e80f72a8 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp @@ -1,73 +1,75 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryTestCase.h" #include #include #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include #endif -berry::TestCase::TestCase(const std::string& testName) : - CppUnit::TestCase(testName), m_LeakDetails(false), +#include + +berry::TestCase::TestCase(const QString& testName) : + CppUnit::TestCase(testName.toStdString()), m_LeakDetails(false), m_IgnoreLeakage(false) { } void berry::TestCase::LeakDetailsOn() { m_LeakDetails = true; } void berry::TestCase::IgnoreLeakingObjects() { BERRY_WARN << "Ignoring Leaking Objects!!"; m_IgnoreLeakage = true; } void berry::TestCase::DoSetUp() { } void berry::TestCase::DoTearDown() { } void berry::TestCase::setUp() { CppUnit::TestCase::setUp(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::ResetObjectSummary(); #endif DoSetUp(); } void berry::TestCase::tearDown() { CppUnit::TestCase::tearDown(); DoTearDown(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER assert(m_IgnoreLeakage || !DebugUtil::PrintObjectSummary(m_LeakDetails)); #endif m_LeakDetails = false; } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.h b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.h index 4a3dfb6afe..bdb1502010 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.h @@ -1,84 +1,84 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYTESTCASE_H_ #define BERRYTESTCASE_H_ #include #include namespace berry { class BERRY_TEST_EXPORT TestCase : public CppUnit::TestCase { public: - TestCase(const std::string& testName); + TestCase(const QString& testName); /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * The default implementation does nothing. * Subclasses may extend. */ virtual void DoSetUp(); /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * The default implementation closes all test windows, processing events both before * and after doing so. * Subclasses may extend. */ virtual void DoTearDown(); /** * Clients should overwrite DoSetUp() instead of this method. */ void setUp(); /** * Clients should overwrite DoSetUp() instead of this method. */ void tearDown(); protected: /** * Call this method in your unit test to enable detailed * output about leaking berry::Object instances. */ void LeakDetailsOn(); /** * Call this method to ignore leaking objects and to continue * with the unit tests. */ void IgnoreLeakingObjects(); private: bool m_LeakDetails; bool m_IgnoreLeakage; }; } #endif /* BERRYTESTCASE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp index f6d0a19b0f..4a13f5839b 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp @@ -1,45 +1,46 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPluginActivator.h" +#include "berryMacros.h" #include "berryCoreTestApplication.h" #include namespace berry { org_blueberry_test_Activator::org_blueberry_test_Activator() { } void org_blueberry_test_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(CoreTestApplication, context) } void org_blueberry_test_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_blueberry_test, berry::org_blueberry_test_Activator) #endif diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.cpp index 6ce4431f59..7e709cd9c3 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.cpp @@ -1,76 +1,68 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryTestDescriptor.h" #include "berryTestRegistry.h" +#include "berryIContributor.h" #include Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") namespace berry { TestDescriptor::TestDescriptor(IConfigurationElement::Pointer elem) : configElem(elem) { } CppUnit::Test* TestDescriptor::CreateTest() { CppUnit::Test* test = configElem->CreateExecutableExtension ( TestRegistry::ATT_CLASS); if (test == 0) { // Try legacy BlueBerry manifests instead test = configElem->CreateExecutableExtension ( - TestRegistry::ATT_CLASS, TestRegistry::TEST_MANIFEST); + TestRegistry::ATT_CLASS); } return test; } -std::string TestDescriptor::GetId() const +QString TestDescriptor::GetId() const { - std::string id; - configElem->GetAttribute(TestRegistry::ATT_ID, id); - return id; + return configElem->GetAttribute(TestRegistry::ATT_ID); } -std::string TestDescriptor::GetContributor() const +QString TestDescriptor::GetContributor() const { - return configElem->GetContributor(); + return configElem->GetContributor()->GetName(); } -std::string TestDescriptor::GetDescription() const +QString TestDescriptor::GetDescription() const { - std::string descr; - configElem->GetAttribute(TestRegistry::ATT_DESCRIPTION, descr); - return descr; + return configElem->GetAttribute(TestRegistry::ATT_DESCRIPTION); } bool TestDescriptor::IsUITest() const { - std::string isUi; - if (configElem->GetAttribute(TestRegistry::ATT_UITEST, isUi)) - { - return !Poco::icompare(isUi, "true"); - } - - return false; + QString isUi = configElem->GetAttribute(TestRegistry::ATT_UITEST); + return isUi.compare("true", Qt::CaseInsensitive); } } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h index 4e766f59de..33ad3ec271 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h @@ -1,49 +1,49 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYTESTDESCRIPTOR_H_ #define BERRYTESTDESCRIPTOR_H_ #include "berryITestDescriptor.h" -#include +#include namespace berry { class TestDescriptor : public ITestDescriptor { public: - berryObjectMacro(TestDescriptor); + berryObjectMacro(TestDescriptor) TestDescriptor(IConfigurationElement::Pointer elem); CppUnit::Test* CreateTest(); - std::string GetId() const; - std::string GetContributor() const; - std::string GetDescription() const; + QString GetId() const; + QString GetContributor() const; + QString GetDescription() const; bool IsUITest() const; private: IConfigurationElement::Pointer configElem; }; } #endif /* BERRYTESTDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.cpp b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.cpp index 9a4734a936..2ef72bacd3 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.cpp @@ -1,63 +1,60 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryTestRegistry.h" #include "berryTestDescriptor.h" #include -#include +#include namespace berry { -const std::string TestRegistry::TAG_TEST = "test"; -const std::string TestRegistry::ATT_ID = "id"; -const std::string TestRegistry::ATT_CLASS = "class"; -const std::string TestRegistry::ATT_DESCRIPTION = "description"; -const std::string TestRegistry::ATT_UITEST = "uitest"; - -const std::string TestRegistry::TEST_MANIFEST = "CppUnitTest"; +const QString TestRegistry::TAG_TEST = "test"; +const QString TestRegistry::ATT_ID = "id"; +const QString TestRegistry::ATT_CLASS = "class"; +const QString TestRegistry::ATT_DESCRIPTION = "description"; +const QString TestRegistry::ATT_UITEST = "uitest"; TestRegistry::TestRegistry() { - std::vector elements( - Platform::GetExtensionPointService()->GetConfigurationElementsFor( + QList elements( + Platform::GetExtensionRegistry()->GetConfigurationElementsFor( "org.blueberry.tests")); - for (std::vector::iterator i = - elements.begin(); i != elements.end(); ++i) + foreach (const IConfigurationElement::Pointer& configElem, elements) { - if ((*i)->GetName() == TAG_TEST) + if (configElem->GetName() == TAG_TEST) { - this->ReadTest(*i); + this->ReadTest(configElem); } } } -const std::vector& -TestRegistry::GetTestsForId(const std::string& pluginid) +const QList& +TestRegistry::GetTestsForId(const QString& pluginid) { return mapIdToTests[pluginid]; } -void TestRegistry::ReadTest(IConfigurationElement::Pointer testElem) +void TestRegistry::ReadTest(const IConfigurationElement::Pointer& testElem) { ITestDescriptor::Pointer descriptor(new TestDescriptor(testElem)); - poco_assert(descriptor->GetId() != ""); + Q_ASSERT(!descriptor->GetId().isEmpty()); mapIdToTests[descriptor->GetContributor()].push_back(descriptor); } } diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h index 4ec11668f2..93e01f6908 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h @@ -1,57 +1,52 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYTESTREGISTRY_H_ #define BERRYTESTREGISTRY_H_ -#include +#include #include "berryITestDescriptor.h" -#include -#include - namespace berry { class TestRegistry { public: - static const std::string TAG_TEST; // = "test" - static const std::string ATT_ID; // = "id" - static const std::string ATT_CLASS; // = "class" - static const std::string ATT_DESCRIPTION; // = "description" - static const std::string ATT_UITEST; // = "uitest" - - static const std::string TEST_MANIFEST; // = "CppUnitTest" + static const QString TAG_TEST; // = "test" + static const QString ATT_ID; // = "id" + static const QString ATT_CLASS; // = "class" + static const QString ATT_DESCRIPTION; // = "description" + static const QString ATT_UITEST; // = "uitest" TestRegistry(); - const std::vector& GetTestsForId(const std::string& pluginid); + const QList& GetTestsForId(const QString& pluginid); protected: - void ReadTest(IConfigurationElement::Pointer testElem); + void ReadTest(const IConfigurationElement::Pointer& testElem); private: - Poco::HashMap > mapIdToTests; + QHash > mapIdToTests; }; } #endif /* BERRYTESTREGISTRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake index fde8abe0d2..77c88fca81 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake @@ -1,468 +1,470 @@ set(SRC_CPP_FILES berryAbstractSourceProvider.cpp berryAbstractUICTKPlugin.cpp berryConstants.cpp berryDisplay.cpp berryEditorPart.cpp berryFileEditorInput.cpp berryGeometry.cpp berryIActionBars.h berryIContextService.cpp berryIContributionRoot.h berryIDropTargetListener.cpp berryIEditorDescriptor.cpp berryIEditorInput.cpp berryIEditorMatchingStrategy.cpp berryIEditorPart.cpp berryIEditorReference.cpp berryIEditorRegistry.cpp berryIEditorSite.cpp berryIFileEditorMapping.cpp berryIFolderLayout.cpp berryImageDescriptor.cpp berryIMemento.cpp berryINullSelectionListener.cpp berryIPageLayout.cpp berryIPartListener.cpp berryIPageService.cpp berryIPartService.cpp berryIPathEditorInput.cpp berryIPerspectiveDescriptor.cpp berryIPerspectiveFactory.cpp berryIPerspectiveListener.cpp berryIPerspectiveRegistry.cpp berryIPlaceholderFolderLayout.cpp berryIPluginContribution.h berryIPostSelectionProvider.cpp berryIPreferencePage.cpp berryIPropertyChangeListener.cpp berryIQtPreferencePage.cpp berryIQtStyleManager.cpp berryIReusableEditor.cpp berryISaveablePart.cpp berryISaveablesLifecycleListener.cpp berryISaveablesSource.cpp berryISelection.cpp berryISelectionChangedListener.cpp berryISelectionListener.cpp berryISelectionProvider.cpp berryISelectionService.cpp berryIShellListener.cpp berryIShellProvider.cpp berryIShowInSource.h berryIShowInTarget.h berryISizeProvider.cpp berryISourceProvider.cpp berryISourceProviderListener.cpp berryISources.cpp berryIStickyViewDescriptor.cpp berryIStructuredSelection.cpp berryIViewCategory.cpp berryIViewDescriptor.cpp berryIViewLayout.cpp berryIViewPart.cpp berryIViewReference.cpp berryIViewRegistry.cpp berryIViewSite.cpp berryIWorkbenchCommandConstants.cpp berryIWindowListener.cpp berryIWorkbench.cpp berryIWorkbenchListener.cpp berryIWorkbenchPage.cpp berryIWorkbenchPart.cpp berryIWorkbenchPartConstants.cpp berryIWorkbenchPartDescriptor.cpp berryIWorkbenchPartReference.cpp berryIWorkbenchPartSite.cpp berryIWorkbenchSite.cpp berryIWorkbenchWindow.cpp berryMenuUtil.cpp berryPlatformUI.cpp berryPoint.cpp berryPropertyChangeEvent.cpp berryQModelIndexObject.cpp berryQtEditorPart.cpp berryQtItemSelection.cpp berryQtIntroPart.cpp berryQtPreferences.cpp berryQtSelectionProvider.cpp berryQtViewPart.cpp berryRectangle.cpp berrySameShellProvider.cpp berrySaveable.cpp berrySaveablesLifecycleEvent.cpp berrySelectionChangedEvent.cpp berryShell.cpp berryShellEvent.cpp berryShowInContext.cpp berryUIException.cpp berryViewPart.cpp berryWindow.cpp berryWorkbenchActionConstants.cpp berryWorkbenchPart.cpp berryWorkbenchPreferenceConstants.cpp berryXMLMemento.cpp #actions actions/berryAbstractContributionFactory.cpp actions/berryAbstractGroupMarker.cpp #actions/berryAction.cpp #actions/berryActionContributionItem.cpp actions/berryCommandContributionItem.h actions/berryCommandContributionItem.cpp actions/berryContributionItem.cpp actions/berryContributionItemFactory.cpp actions/berryContributionManager.cpp actions/berryIContributionItem.h actions/berryIContributionManager.h actions/berryIContributionManagerOverrides.cpp actions/berryIMenuManager.h - #actions/berryManuBarManager.cpp + #actions/berryMenuBarManager.cpp actions/berryMenuManager.cpp actions/berrySeparator.cpp actions/berrySubContributionItem.cpp #application application/berryActionBarAdvisor.cpp application/berryIActionBarConfigurer.cpp application/berryIWorkbenchConfigurer.cpp application/berryIWorkbenchWindowConfigurer.cpp application/berryWorkbenchAdvisor.cpp application/berryWorkbenchWindowAdvisor.cpp #commands commands/berryICommandImageService.cpp commands/berryICommandService.cpp commands/berryIElementReference.h commands/berryIElementUpdater.h commands/berryIMenuService.h commands/berryUIElement.cpp #dialogs dialogs/berryIDialog.cpp dialogs/berryIShowViewDialog.cpp dialogs/berryMessageDialog.cpp #guitk guitk/berryGuiTkControlEvent.cpp guitk/berryGuiTkEvent.cpp guitk/berryGuiTkIControlListener.cpp guitk/berryGuiTkIMenuListener.cpp guitk/berryGuiTkISelectionListener.cpp guitk/berryGuiTkSelectionEvent.cpp #handlers handlers/berryHandlerUtil.cpp handlers/berryIHandlerActivation.cpp handlers/berryIHandlerService.cpp handlers/berryRadioState.cpp handlers/berryRegistryToggleState.cpp handlers/berryShowViewHandler.cpp handlers/berryToggleState.cpp #intro intro/berryIIntroManager.cpp intro/berryIIntroPart.cpp intro/berryIIntroSite.cpp intro/berryIntroPart.cpp #tweaklets tweaklets/berryDnDTweaklet.cpp tweaklets/berryGuiWidgetsTweaklet.cpp tweaklets/berryImageTweaklet.cpp tweaklets/berryMessageDialogTweaklet.cpp tweaklets/berryITracker.cpp tweaklets/berryWorkbenchPageTweaklet.cpp tweaklets/berryWorkbenchTweaklet.cpp #presentations presentations/berryIPresentablePart.cpp presentations/berryIPresentationFactory.cpp presentations/berryIPresentationSerializer.cpp presentations/berryIStackPresentationSite.cpp presentations/berryStackDropResult.cpp presentations/berryStackPresentation.cpp #services services/berryIDisposable.cpp services/berryIEvaluationReference.h services/berryIEvaluationService.cpp services/berryINestable.cpp services/berryIServiceFactory.cpp services/berryIServiceLocator.cpp services/berryIServiceScopes.cpp services/berryIServiceWithSources.cpp services/berryISourceProviderService.cpp #testing testing/berryTestableObject.cpp #util util/berryISafeRunnableRunner.cpp util/berrySafeRunnable.cpp # application application/berryQtWorkbenchAdvisor.cpp ) set(INTERNAL_CPP_FILES defaultpresentation/berryEmptyTabFolder.cpp defaultpresentation/berryEmptyTabItem.cpp defaultpresentation/berryNativeTabFolder.cpp defaultpresentation/berryNativeTabItem.cpp defaultpresentation/berryQCTabBar.cpp defaultpresentation/berryQtWorkbenchPresentationFactory.cpp util/berryAbstractTabFolder.cpp util/berryAbstractTabItem.cpp util/berryIPresentablePartList.cpp util/berryLeftToRightTabOrder.cpp util/berryPartInfo.cpp util/berryPresentablePartFolder.cpp util/berryReplaceDragHandler.cpp util/berryTabbedStackPresentation.cpp util/berryTabDragHandler.cpp util/berryTabFolderEvent.cpp util/berryTabOrder.cpp #intro intro/berryEditorIntroAdapterPart.cpp intro/berryIIntroDescriptor.cpp intro/berryIIntroRegistry.cpp intro/berryIntroConstants.cpp intro/berryIntroDescriptor.cpp intro/berryIntroPartAdapterSite.cpp intro/berryIntroRegistry.cpp intro/berryViewIntroAdapterPart.cpp intro/berryWorkbenchIntroManager.cpp berryAbstractMenuAdditionCacheEntry.cpp berryAbstractPartSelectionTracker.cpp berryAbstractSelectionService.cpp berryActivePartExpression.cpp berryAlwaysEnabledExpression.cpp berryAndExpression.cpp berryBundleUtility.cpp berryCommandContributionItemParameter.cpp berryCommandParameter.cpp berryCommandPersistence.cpp berryCommandService.cpp berryCommandServiceFactory.cpp berryCommandStateProxy.cpp berryCompositeExpression.cpp berryContainerPlaceholder.cpp berryContributionRoot.cpp berryDetachedPlaceHolder.cpp berryDefaultSaveable.cpp berryDefaultStackPresentationSite.cpp berryDetachedWindow.cpp berryDragUtil.cpp berryEditorAreaHelper.cpp berryEditorDescriptor.cpp berryEditorManager.cpp berryEditorReference.cpp berryEditorRegistry.cpp berryEditorRegistryReader.cpp berryEditorSashContainer.cpp berryEditorSite.cpp berryElementReference.cpp berryErrorViewPart.cpp berryEvaluationAuthority.cpp berryEvaluationReference.cpp berryEvaluationResultCache.cpp berryEvaluationService.cpp berryExpressionAuthority.cpp berryFileEditorMapping.cpp berryFolderLayout.cpp berryHandlerActivation.cpp berryHandlerAuthority.cpp berryHandlerPersistence.cpp berryHandlerProxy.cpp berryHandlerService.cpp berryHandlerServiceFactory.cpp berryIDragOverListener.cpp berryIDropTarget.cpp berryIEvaluationResultCache.cpp berryILayoutContainer.cpp berryInternalMenuService.h berryIServiceLocatorCreator.cpp berryIStickyViewManager.cpp berryIWorkbenchLocationService.cpp berryLayoutHelper.cpp berryLayoutPart.cpp berryLayoutPartSash.cpp berryLayoutTree.cpp berryLayoutTreeNode.cpp berryMenuServiceFactory.cpp berryMMMenuListener.cpp berryNestableHandlerService.cpp berryNullEditorInput.cpp berryPageLayout.cpp berryPagePartSelectionTracker.cpp berryPageSelectionService.cpp berryParameterValueConverterProxy.cpp berryPartList.cpp berryPartPane.cpp berryPartPlaceholder.cpp berryPartSashContainer.cpp berryPartService.cpp berryPartSite.cpp berryPartStack.cpp berryPartTester.cpp berryPersistentState.cpp berryPerspective.cpp berryPerspectiveDescriptor.cpp berryPerspectiveExtensionReader.cpp berryPerspectiveHelper.cpp berryPerspectiveRegistry.cpp berryPerspectiveRegistryReader.cpp berryPlaceholderFolderLayout.cpp berryPreferenceConstants.cpp berryPresentablePart.cpp berryPresentationFactoryUtil.cpp berryPresentationSerializer.cpp berryQtControlWidget.cpp berryQtDnDControlWidget.cpp berryQtDisplay.cpp berryQtDnDTweaklet.cpp berryQtFileImageDescriptor.cpp berryQtGlobalEventFilter.cpp berryQtIconImageDescriptor.cpp berryQtImageTweaklet.cpp berryQtMainWindowControl.cpp berryQtMessageDialogTweaklet.cpp berryQtMissingImageDescriptor.cpp berryQtOpenPerspectiveAction.cpp berryQtPerspectiveSwitcher.cpp berryQtSafeApplication.cpp berryQtSash.cpp berryQtShell.cpp berryQtShowViewAction.cpp berryQtShowViewDialog.cpp berryQtStyleManager.cpp berryQtStylePreferencePage.cpp berryQtTracker.cpp berryQtWidgetController.cpp berryQtWidgetsTweaklet.cpp berryQtWidgetsTweakletImpl.cpp berryQtWorkbenchPageTweaklet.cpp berryQtWorkbenchTweaklet.cpp berryRegistryPersistence.cpp berryRegistryReader.cpp berrySaveablesList.cpp berryShowViewMenu.cpp berryServiceLocator.cpp berryServiceLocatorCreator.cpp berryShellPool.cpp berrySlaveCommandService.cpp berrySlaveHandlerService.cpp berrySlaveMenuService.cpp berrySourceProviderService.cpp berrySourcePriorityNameMapping.cpp berryStatusUtil.cpp berryStickyViewDescriptor.cpp berryStickyViewManager.cpp berryTweaklets.cpp berryUtil.cpp berryViewDescriptor.cpp berryViewFactory.cpp berryViewLayout.cpp berryViewReference.cpp berryViewRegistry.cpp berryViewRegistryReader.cpp berryViewSashContainer.cpp berryViewSite.cpp berryWorkbenchPage.cpp berryWindowManager.cpp berryWindowPartSelectionTracker.cpp berryWindowSelectionService.cpp berryWorkbench.cpp berryWorkbenchConfigurer.cpp berryWorkbenchConstants.cpp berryWorkbenchLocationService.cpp berryWorkbenchMenuService.cpp berryWorkbenchPagePartList.cpp berryWorkbenchPartReference.cpp berryWorkbenchPlugin.cpp berryWorkbenchRegistryConstants.cpp berryWorkbenchServiceRegistry.cpp berryWorkbenchSourceProvider.cpp berryWorkbenchTestable.cpp berryWorkbenchWindow.cpp berryWorkbenchWindowConfigurer.cpp berryWorkbenchWindowExpression.cpp berryWWinActionBars.cpp berryWWinPartService.cpp ) set(MOC_H_FILES + src/berryAbstractUICTKPlugin.h src/berryEditorPart.h src/berryQtSelectionProvider.h src/berryViewPart.h src/berryWorkbenchPart.h src/actions/berryCommandContributionItem.h src/intro/berryIntroPart.h src/handlers/berryShowViewHandler.h src/internal/berryCommandServiceFactory.h src/internal/berryHandlerServiceFactory.h src/internal/berryMenuServiceFactory.h src/internal/berryMMMenuListener.h - src/internal/berryWorkbenchSourceProvider.h src/internal/berryQtDisplay.h src/internal/berryQtDnDTweaklet.h src/internal/berryQtGlobalEventFilter.h src/internal/berryQtImageTweaklet.h src/internal/berryQtMainWindowControl.h src/internal/berryQtMessageDialogTweaklet.h src/internal/berryQtOpenPerspectiveAction.h src/internal/berryQtPerspectiveSwitcher.h src/internal/berryQtSash.h src/internal/berryQtShowViewAction.h src/internal/berryQtStyleManager.h src/internal/berryQtStylePreferencePage.h src/internal/berryQtTracker.h src/internal/berryQtWidgetsTweaklet.h src/internal/berryQtWidgetsTweakletImpl.h src/internal/berryQtWorkbenchTweaklet.h src/internal/berryQtWorkbenchPageTweaklet.h + src/internal/berryWorkbenchPlugin.h + src/internal/berryWorkbenchSourceProvider.h src/internal/defaultpresentation/berryNativeTabFolder.h src/internal/defaultpresentation/berryNativeTabItem.h src/internal/defaultpresentation/berryQCTabBar.h src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h src/internal/intro/berryEditorIntroAdapterPart.h ) set(UI_FILES src/internal/berryQtShowViewDialog.ui src/internal/berryQtStylePreferencePage.ui src/internal/berryQtStatusPart.ui ) set(QRC_FILES resources/org_blueberry_ui_qt.qrc ) set(CACHED_RESOURCE_FILES plugin.xml ) set(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h index ab4218e075..60ea407751 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h @@ -1,331 +1,332 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYABSTRACTUICTKPLUGIN_H_ #define BERRYABSTRACTUICTKPLUGIN_H_ #include #include namespace berry { template class SmartPointer; struct IPreferences; struct IPreferencesService; struct IWorkbench; struct ImageDescriptor; /** * \ingroup org_blueberry_ui_qt * * Abstract base class for plug-ins that integrate with the BlueBerry platform UI. *

* Subclasses obtain the following capabilities: *

*

* Preferences *

    *
  • The platform core runtime contains general support for plug-in * preferences (org.blueberry.core.runtime.Preferences). * This class provides appropriate conversion to the older JFace preference * API (org.blueberry.jface.preference.IPreferenceStore).
  • *
  • The method getPreferenceStore returns the JFace preference * store (cf. Plugin.getPluginPreferences which returns * a core runtime preferences object.
  • *
  • Subclasses may reimplement initializeDefaultPreferences * to set up any default values for preferences using JFace API. In this * case, initializeDefaultPluginPreferences should not be * overridden.
  • *
  • Subclasses may reimplement * initializeDefaultPluginPreferences to set up any default * values for preferences using core runtime API. In this * case, initializeDefaultPreferences should not be * overridden.
  • *
  • Preferences are also saved automatically on plug-in shutdown. * However, saving preferences immediately after changing them is * strongly recommended, since that ensures that preference settings * are not lost even in the event of a platform crash.
  • *
* Dialogs *
    *
  • The dialog store is read the first time getDialogSettings * is called.
  • *
  • The dialog store allows the plug-in to "record" important choices made * by the user in a wizard or dialog, so that the next time the * wizard/dialog is used the widgets can be defaulted to better values. A * wizard could also use it to record the last 5 values a user entered into * an editable combo - to show "recent values".
  • *
  • The dialog store is found in the file whose name is given by the * constant FN_DIALOG_STORE. A dialog store file is first * looked for in the plug-in's read/write state area; if not found there, * the plug-in's install directory is checked. * This allows a plug-in to ship with a read-only copy of a dialog store * file containing initial values for certain settings.
  • *
  • Plug-in code can call saveDialogSettings to cause settings to * be saved in the plug-in's read/write state area. A plug-in may opt to do * this each time a wizard or dialog is closed to ensure the latest * information is always safe on disk.
  • *
  • Dialog settings are also saved automatically on plug-in shutdown.
  • *
* Images *
    *
  • A typical UI plug-in will have some images that are used very frequently * and so need to be cached and shared. The plug-in's image registry * provides a central place for a plug-in to store its common images. * Images managed by the registry are created lazily as needed, and will be * automatically disposed of when the plug-in shuts down. Note that the * number of registry images should be kept to a minimum since many OSs * have severe limits on the number of images that can be in memory at once. *
*

* For easy access to your plug-in object, use the singleton pattern. Declare a * static variable in your plug-in class for the singleton. Store the first * (and only) instance of the plug-in class in the singleton when it is created. * Then access the singleton when needed through a static getDefault * method. *

*

* See the description on {@link Plugin}. *

*/ class BERRY_UI_QT AbstractUICTKPlugin : public Plugin { + Q_OBJECT private: /** * The name of the dialog settings file (value * "dialog_settings.xml"). */ static const QString FN_DIALOG_SETTINGS; /** * Storage for dialog and wizard data; null if not yet * initialized. */ //DialogSettings dialogSettings = null; /** * Storage for preferences. */ mutable IPreferencesService* preferencesService; /** * The registry for all graphic images; null if not yet * initialized. */ //ImageRegistry imageRegistry = null; /** * The bundle listener used for kicking off refreshPluginActions(). */ //BundleListener bundleListener; public: /** * Creates an abstract UI plug-in runtime object. *

* Plug-in runtime classes are ctkPluginActivators and so must * have an default constructor. This method is called by the runtime when * the associated bundle is being activated. */ AbstractUICTKPlugin(); /** * Returns the dialog settings for this UI plug-in. * The dialog settings is used to hold persistent state data for the various * wizards and dialogs of this plug-in in the context of a workbench. *

* If an error occurs reading the dialog store, an empty one is quietly created * and returned. *

*

* Subclasses may override this method but are not expected to. *

* * @return the dialog settings */ // IDialogSettings getDialogSettings(); /** * Returns the image registry for this UI plug-in. *

* The image registry contains the images used by this plug-in that are very * frequently used and so need to be globally shared within the plug-in. Since * many OSs have a severe limit on the number of images that can be in memory at * any given time, a plug-in should only keep a small number of images in their * registry. *

* Subclasses should reimplement initializeImageRegistry if they have * custom graphic images to load. *

*

* Subclasses may override this method but are not expected to. *

* * @return the image registry */ // ImageRegistry getImageRegistry(); /** * Returns the preferences service for this UI plug-in. * This preferences service is used to hold persistent settings for this plug-in in * the context of a workbench. Some of these settings will be user controlled, * whereas others may be internal setting that are never exposed to the user. *

* If an error occurs reading the preferences service, an empty preference service is * quietly created, initialized with defaults, and returned. *

* * @return the preferences service */ IPreferencesService* GetPreferencesService() const; SmartPointer GetPreferences() const; /** * Returns the Platform UI workbench. *

* This method exists as a convenience for plugin implementors. The * workbench can also be accessed by invoking PlatformUI.getWorkbench(). *

* @return IWorkbench the workbench for this plug-in */ IWorkbench* GetWorkbench(); protected: /** * Returns a new image registry for this plugin-in. The registry will be * used to manage images which are frequently used by the plugin-in. *

* The default implementation of this method creates an empty registry. * Subclasses may override this method if needed. *

* * @return ImageRegistry the resulting registry. * @see #getImageRegistry */ // ImageRegistry createImageRegistry(); /** * Initializes an image registry with images which are frequently used by the * plugin. *

* The image registry contains the images used by this plug-in that are very * frequently used and so need to be globally shared within the plug-in. Since * many OSs have a severe limit on the number of images that can be in memory * at any given time, each plug-in should only keep a small number of images in * its registry. *

* Implementors should create a JFace image descriptor for each frequently used * image. The descriptors describe how to create/find the image should it be needed. * The image described by the descriptor is not actually allocated until someone * retrieves it. *

* Subclasses may override this method to fill the image registry. *

* @param reg the registry to initalize * * @see #getImageRegistry */ // void initializeImageRegistry(ImageRegistry reg); /** * Loads the dialog settings for this plug-in. * The default implementation first looks for a standard named file in the * plug-in's read/write state area; if no such file exists, the plug-in's * install directory is checked to see if one was installed with some default * settings; if no file is found in either place, a new empty dialog settings * is created. If a problem occurs, an empty settings is silently used. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void loadDialogSettings(); /** * Refreshes the actions for the plugin. * This method is called from startup. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void refreshPluginActions(); /** * Saves this plug-in's dialog settings. * Any problems which arise are silently ignored. */ // void saveDialogSettings(); public: /** * The AbstractUIPlugin implementation of this Plugin * method refreshes the plug-in actions. Subclasses may extend this method, * but must send super first. */ void start(ctkPluginContext* context); /** * The AbstractUIPlugin implementation of this Plugin * method saves this plug-in's preference and dialog stores and shuts down * its image registry (if they are in use). Subclasses may extend this * method, but must send super last. A try-finally statement should * be used where necessary to ensure that super.shutdown() is * always done. */ void stop(ctkPluginContext* context); /** * Creates and returns a new image descriptor for an image file located * within the specified plug-in. *

* This is a convenience method that simply locates the image file in * within the plug-in (no image registries are involved). The path is * relative to the root of the plug-in, and takes into account files * coming from plug-in fragments. The path may include $arg$ elements. * However, the path must not have a leading "." or path separator. * Clients should use a path like "icons/mysample.gif" rather than * "./icons/mysample.gif" or "/icons/mysample.gif". *

* * @param pluginId the id of the plug-in containing the image file; * null is returned if the plug-in does not exist * @param imageFilePath the relative path of the image file, relative to the * root of the plug-in; the path must be legal * @return an image descriptor, or null if no image * could be found * @since 3.0 */ static SmartPointer ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath); }; } // namespace berry #endif /*BERRYABSTRACTUICTKPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h index ff6426a977..2ec27bd1df 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h @@ -1,124 +1,124 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPERSPECTIVEDESCRIPTOR_H_ #define BERRYIPERSPECTIVEDESCRIPTOR_H_ #include #include #include #include "berryImageDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * A perspective descriptor describes a perspective in an * IPerspectiveRegistry. *

* A perspective is a template for view visibility, layout, and action visibility * within a workbench page. There are two types of perspective: a predefined * perspective and a custom perspective. *

    *
  • A predefined perspective is defined by an extension to the workbench's * perspective extension point ("org.blueberry.ui.perspectives"). * The extension defines a id, label, and IPerspectiveFactory. * A perspective factory is used to define the initial layout for a page. *
  • *
  • A custom perspective is defined by the user. In this case a predefined * perspective is modified to suit a particular task and saved as a new * perspective. The attributes for the perspective are stored in a separate file * in the workbench's metadata directory. *
  • *
*

*

* Within a page the user can open any of the perspectives known * to the workbench's perspective registry, typically by selecting one from the * workbench's Open Perspective menu. When selected, the views * and actions within the active page rearrange to reflect the perspective. *

*

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

* @see IPerspectiveRegistry * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPerspectiveDescriptor : public Object { berryObjectMacro(berry::IPerspectiveDescriptor) virtual ~IPerspectiveDescriptor(); /** * Returns the description of this perspective. * This is the value of its "description" attribute. * * @return the description * @since 3.0 */ virtual QString GetDescription() const = 0; /** * Returns this perspective's id. For perspectives declared via an extension, * this is the value of its "id" attribute. * * @return the perspective id */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image to show for this perspective. * If the extension for this perspective specifies an image, the descriptor * for it is returned. Otherwise a default image is returned. * * @return the descriptor of the image to show for this perspective */ virtual ImageDescriptor::Pointer GetImageDescriptor() const = 0; /** * Returns this perspective's label. For perspectives declared via an extension, * this is the value of its "label" attribute. * * @return the label */ virtual QString GetLabel() const = 0; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ virtual bool IsPredefined() const = 0; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ - virtual std::vector GetCategoryPath() = 0; + virtual QStringList GetCategoryPath() const = 0; - virtual std::vector< std::string> GetKeywordReferences() const = 0; + virtual QStringList GetKeywordReferences() const = 0; }; } #endif /*BERRYIPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.cpp index 9f821a8320..5f48d52ed6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.cpp @@ -1,25 +1,26 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIPerspectiveRegistry.h" namespace berry { IPerspectiveRegistry::~IPerspectiveRegistry() { } + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h index 83a25476b1..ad1f0adb69 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h @@ -1,143 +1,138 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPERSPECTIVEREGISTRY_H_ #define BERRYIPERSPECTIVEREGISTRY_H_ #include "berryIPerspectiveDescriptor.h" #include namespace berry { /** * \ingroup org_blueberry_ui * * The workbench's global registry of perspectives. *

* This registry contains a descriptor for each perspectives in the workbench. * It is initially populated with stock perspectives from the workbench's * perspective extension point ("org.blueberry.ui.perspectives") and * with custom perspectives defined by the user. *

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

* @see IWorkbench#getPerspectiveRegistry * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPerspectiveRegistry { - virtual ~IPerspectiveRegistry(); - - /** - * Create a new perspective. - * - * @param label - * the name of the new descriptor - * @param originalDescriptor - * the descriptor on which to base the new descriptor - * @return a new perspective descriptor or null if the - * creation failed. - */ - virtual IPerspectiveDescriptor::Pointer CreatePerspective(const std::string& label, - IPerspectiveDescriptor::Pointer originalDescriptor) = 0; - - /** - * Clones an existing perspective. - * - * @param id the id for the cloned perspective, which must not already be used by - * any registered perspective - * @param label the label assigned to the cloned perspective - * @param desc the perspective to clone - * @return the cloned perspective descriptor - * @throws IllegalArgumentException if there is already a perspective with the given id - * - * @since 3.0 - */ - virtual IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, - IPerspectiveDescriptor::Pointer desc) = 0; + virtual ~IPerspectiveRegistry(); + + /** + * Create a new perspective. + * + * @param label + * the name of the new descriptor + * @param originalDescriptor + * the descriptor on which to base the new descriptor + * @return a new perspective descriptor or null if the + * creation failed. + */ + virtual IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, + IPerspectiveDescriptor::Pointer originalDescriptor) = 0; + + /** + * Clones an existing perspective. + * + * @param id the id for the cloned perspective, which must not already be used by + * any registered perspective + * @param label the label assigned to the cloned perspective + * @param desc the perspective to clone + * @return the cloned perspective descriptor + * @throws IllegalArgumentException if there is already a perspective with the given id + */ + virtual IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, + IPerspectiveDescriptor::Pointer desc) = 0; /** * Deletes a perspective. Has no effect if the perspective is defined in an * extension. * * @param persp the perspective to delete - * @since 3.2 */ virtual void DeletePerspective(IPerspectiveDescriptor::Pointer persp) = 0; - /** - * Finds and returns the registered perspective with the given perspective id. - * - * @param perspectiveId the perspective id - * @return the perspective, or null if none - * @see IPerspectiveDescriptor#getId - */ - virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& perspectiveId) = 0; - - /** - * Finds and returns the registered perspective with the given label. - * - * @param label the label - * @return the perspective, or null if none - * @see IPerspectiveDescriptor#getLabel - */ - virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label) = 0; - - /** - * Returns the id of the default perspective for the workbench. This identifies one - * perspective extension within the workbench's perspective registry. - *

- * Returns null if there is no default perspective. - *

- * - * @return the default perspective id, or null - */ - virtual QString GetDefaultPerspective() = 0; - - /** - * Returns a list of the perspectives known to the workbench. - * - * @return a list of perspectives - */ - virtual QList GetPerspectives() = 0; - - /** - * Sets the default perspective for the workbench to the given perspective id. - * If non-null, the id must correspond to a perspective extension - * within the workbench's perspective registry. - *

- * A null id indicates no default perspective. - *

- * - * @param id a perspective id, or null - */ - virtual void SetDefaultPerspective(const QString& id) = 0; - - /** - * Reverts a perspective back to its original definition - * as specified in the plug-in manifest. - * - * @param perspToRevert the perspective to revert - * - * @since 3.0 - */ - virtual void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) = 0; + /** + * Finds and returns the registered perspective with the given perspective id. + * + * @param perspectiveId the perspective id + * @return the perspective, or null if none + * @see IPerspectiveDescriptor#getId + */ + virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& perspectiveId) = 0; + + /** + * Finds and returns the registered perspective with the given label. + * + * @param label the label + * @return the perspective, or null if none + * @see IPerspectiveDescriptor#getLabel + */ + virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label) = 0; + + /** + * Returns the id of the default perspective for the workbench. This identifies one + * perspective extension within the workbench's perspective registry. + *

+ * Returns null if there is no default perspective. + *

+ * + * @return the default perspective id, or null + */ + virtual QString GetDefaultPerspective() = 0; + + /** + * Returns a list of the perspectives known to the workbench. + * + * @return a list of perspectives + */ + virtual QList GetPerspectives() = 0; + + /** + * Sets the default perspective for the workbench to the given perspective id. + * If non-null, the id must correspond to a perspective extension + * within the workbench's perspective registry. + *

+ * A null id indicates no default perspective. + *

+ * + * @param id a perspective id, or null + */ + virtual void SetDefaultPerspective(const QString& id) = 0; + + /** + * Reverts a perspective back to its original definition + * as specified in the plug-in manifest. + * + * @param perspToRevert the perspective to revert + */ + virtual void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) = 0; }; } #endif /*BERRYIPERSPECTIVEREGISTRY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h index 8d34d15f69..9a99615885 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h @@ -1,109 +1,106 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIVIEWDESCRIPTOR_H_ #define BERRYIVIEWDESCRIPTOR_H_ #include #include "berryIWorkbenchPartDescriptor.h" #include "berryIViewPart.h" #include #include #include "berryImageDescriptor.h" -#include -#include - namespace berry { /** * \ingroup org_blueberry_ui_qt * * This is a view descriptor. It provides a "description" of a given * given view so that the view can later be constructed. *

* The view registry provides facilities to map from an extension * to a IViewDescriptor. *

*

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

* * @see org.blueberry.ui.IViewRegistry */ struct BERRY_UI_QT IViewDescriptor : public IWorkbenchPartDescriptor, public IAdaptable { berryObjectMacro(berry::IViewDescriptor) ~IViewDescriptor(); /** * Creates an instance of the view defined in the descriptor. * * @return the view part * @throws CoreException thrown if there is a problem creating the part */ virtual IViewPart::Pointer CreateView() = 0; - virtual std::vector< std::string> GetKeywordReferences() const = 0; + virtual QStringList GetKeywordReferences() const = 0; /** * Returns an array of strings that represent * view's category path. This array will be used * for hierarchical presentation of the * view in places like submenus. * @return array of category tokens or null if not specified. */ - virtual const QList& GetCategoryPath() const = 0; + virtual QStringList GetCategoryPath() const = 0; /** * Returns the description of this view. * * @return the description */ virtual QString GetDescription() const = 0; /** * Returns the descriptor for the icon to show for this view. */ virtual SmartPointer GetImageDescriptor() const = 0; /** * Returns whether this view allows multiple instances. * * @return whether this view allows multiple instances */ virtual bool GetAllowMultiple() const = 0; /** * Returns whether this view can be restored upon workbench restart. * * @return whether whether this view can be restored upon workbench restart */ virtual bool IsRestorable() const = 0; virtual bool operator==(const Object*) const = 0; }; } #endif /*BERRYIVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h index 5a13e28c6e..21f7db8adf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h @@ -1,854 +1,854 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIWORKBENCHPAGE_H_ #define BERRYIWORKBENCHPAGE_H_ #include #include "berryIEditorReference.h" #include "berryIViewReference.h" #include "berryIPerspectiveDescriptor.h" #include "berryIEditorPart.h" #include "berryIViewPart.h" #include "berryIEditorInput.h" #include "berryIPartService.h" #include "berryISelectionService.h" #include "berryIReusableEditor.h" #include "berryIWorkbenchWindow.h" /** * \ingroup org_blueberry_ui_qt * */ namespace berry { /** * A workbench page consists of an arrangement of views and editors intended to * be presented together to the user in a single workbench window. *

* A page can contain 0 or more views and 0 or more editors. These views and * editors are contained wholly within the page and are not shared with other * pages. The layout and visible action set for the page is defined by a * perspective. *

* The number of views and editors within a page is restricted to simplify part * management for the user. In particular: *

    *
  • Unless a view explicitly allows for multiple instances in its plugin * declaration there will be only one instance in a given workbench page.
  • *
  • Only one editor can exist for each editor input within a page. *
  • *
*

*

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

* * @see IPerspectiveDescriptor * @see IEditorPart * @see IViewPart */ struct BERRY_UI_QT IWorkbenchPage : public IPartService, public ISelectionService, public Object { berryObjectMacro(berry::IWorkbenchPage) ~IWorkbenchPage(); /** * An optional attribute within a workspace marker (IMarker) * which identifies the preferred editor type to be opened when * openEditor is called. * * @see #openEditor(IEditorInput, String) * @see #openEditor(IEditorInput, String, boolean) * @deprecated in 3.0 since the notion of markers this is not generally * applicable. Use the IDE-specific constant * IDE.EDITOR_ID_ATTR. */ static const QString EDITOR_ID_ATTR; // = "org.blueberry.ui.editorID"; /** * Change event id when the perspective is reset to its original state. * * @see IPerspectiveListener */ static const QString CHANGE_RESET; // = "reset"; /** * Change event id when the perspective has completed a reset to its * original state. * * @since 3.0 * @see IPerspectiveListener */ static const QString CHANGE_RESET_COMPLETE; // = "resetComplete"; /** * Change event id when one or more views are shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_VIEW_SHOW; // = "viewShow"; /** * Change event id when one or more views are hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_VIEW_HIDE; // = "viewHide"; /** * Change event id when one or more editors are opened in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_OPEN; // = "editorOpen"; /** * Change event id when one or more editors are closed in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_CLOSE; // = "editorClose"; /** * Change event id when the editor area is shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_AREA_SHOW; // = "editorAreaShow"; /** * Change event id when the editor area is hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_AREA_HIDE; // = "editorAreaHide"; /** * Change event id when an action set is shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_ACTION_SET_SHOW; // = "actionSetShow"; /** * Change event id when an action set is hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_ACTION_SET_HIDE; // = "actionSetHide"; /** * Show view mode that indicates the view should be made visible and * activated. Use of this mode has the same effect as calling * {@link #showView(String)}. */ static const int VIEW_ACTIVATE; // = 1; /** * Show view mode that indicates the view should be made visible. If the * view is opened in the container that contains the active view then this * has the same effect as VIEW_CREATE. */ static const int VIEW_VISIBLE; // = 2; /** * Show view mode that indicates the view should be made created but not * necessarily be made visible. It will only be made visible in the event * that it is opened in its own container. In other words, only if it is not * stacked with another view. */ static const int VIEW_CREATE; // = 3; /** * Editor opening match mode specifying that no matching against existing * editors should be done. */ static const int MATCH_NONE; // = 0; /** * Editor opening match mode specifying that the editor input should be * considered when matching against existing editors. */ static const int MATCH_INPUT; // = 1; /** * Editor opening match mode specifying that the editor id should be * considered when matching against existing editors. */ static const int MATCH_ID; // = 2; /** * Activates the given part. The part will be brought to the front and given * focus. The part must belong to this page. * * @param part * the part to activate */ virtual void Activate(IWorkbenchPart::Pointer part) = 0; /** * Adds a property change listener. * * @param listener * the property change listener to add */ //virtual void addPropertyChangeListener(IPropertyChangeListener listener); /** * Moves the given part forward in the Z order of this page so as to make it * visible, without changing which part has focus. The part must belong to * this page. * * @param part * the part to bring forward */ virtual void BringToTop(IWorkbenchPart::Pointer part) = 0; /** * Closes this workbench page. If this page is the active one, this honor is * passed along to one of the window's other pages if possible. *

* If the page has an open editor with unsaved content, the user will be * given the opportunity to save it. *

* * @return true if the page was successfully closed, and * false if it is still open */ virtual bool Close() = 0; /** * Closes all of the editors belonging to this workbench page. *

* If the page has open editors with unsaved content and save * is true, the user will be given the opportunity to save * them. *

* * @param save * * @return true if all editors were successfully closed, and * false if at least one is still open */ virtual bool CloseAllEditors(bool save) = 0; /** * Closes the given Array of editor references. The editors * must belong to this workbench page. *

* If any of the editors have unsaved content and save is * true, the user will be given the opportunity to save * them. *

* * @param editorRefs * the editors to close * @param save * true to save the editor contents if required * (recommended), and false to discard any unsaved * changes * @return true if the editors were successfully closed, and * false if the editors are still open */ virtual bool CloseEditors(const QList& editorRefs, bool save) = 0; /** * Closes the given editor. The editor must belong to this workbench page. *

* If the editor has unsaved content and save is * true, the user will be given the opportunity to save it. *

* * @param editor * the editor to close * @param save * true to save the editor contents if required * (recommended), and false to discard any unsaved * changes * @return true if the editor was successfully closed, and * false if the editor is still open */ virtual bool CloseEditor(IEditorPart::Pointer editor, bool save) = 0; /** * Returns the view in this page with the specified id. There is at most one * view in the page with the specified id. * * @param viewId * the id of the view extension to use * @return the view, or null if none is found */ virtual IViewPart::Pointer FindView(const QString& viewId) = 0; /** * Returns the view reference with the specified id. * * @param viewId * the id of the view extension to use * @return the view reference, or null if none is found */ virtual IViewReference::Pointer FindViewReference(const QString& viewId) = 0; /** * Returns the view reference with the specified id and secondary id. * * @param viewId * the id of the view extension to use * @param secondaryId * the secondary id to use, or null for no * secondary id * @return the view reference, or null if none is found */ virtual IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId) = 0; /** * Returns the active editor open in this page. *

* This is the visible editor on the page, or, if there is more than one * visible editor, this is the one most recently brought to top. *

* * @return the active editor, or null if no editor is active */ virtual IEditorPart::Pointer GetActiveEditor() = 0; /** * Returns the editor with the specified input. Returns null if there is no * opened editor with that input. * * @param input * the editor input * @return an editor with input equals to input */ virtual IEditorPart::Pointer FindEditor(IEditorInput::Pointer input) = 0; /** * Returns an array of editor references that match the given input and/or * editor id, as specified by the given match flags. Returns an empty array * if there are no matching editors, or if matchFlags is MATCH_NONE. * * @param input * the editor input, or null if MATCH_INPUT is not * specified in matchFlags * @param editorId * the editor id, or null if MATCH_ID is not * specified in matchFlags * @param matchFlags * a bit mask consisting of zero or more of the MATCH_* constants * OR-ed together * @return the references for the matching editors * * @see #MATCH_NONE * @see #MATCH_INPUT * @see #MATCH_ID */ virtual QList FindEditors(IEditorInput::Pointer input, const QString& editorId, int matchFlags) = 0; /** * Returns a list of the editors open in this page. *

* Note that each page has its own editors; editors are never shared between * pages. *

* * @return a list of open editors * * @deprecated use #getEditorReferences() instead */ virtual QList GetEditors() = 0; /** * Returns an array of references to open editors in this page. *

* Note that each page has its own editors; editors are never shared between * pages. *

* * @return a list of open editors */ virtual QList GetEditorReferences() = 0; /** * Returns a list of dirty editors in this page. * * @return a list of dirty editors */ virtual QList GetDirtyEditors() = 0; /** * Returns the input for this page. * * @return the input for this page, or null if none */ virtual IAdaptable* GetInput() = 0; /** * Returns the page label. This will be a unique identifier within the * containing workbench window. * * @return the page label */ virtual QString GetLabel() = 0; /** * Returns the current perspective descriptor for this page, or * null if there is no current perspective. * * @return the current perspective descriptor or null * @see #setPerspective * @see #savePerspective */ virtual IPerspectiveDescriptor::Pointer GetPerspective() = 0; /** * Returns a list of the reference to views visible on this page. *

* Note that each page has its own views; views are never shared between * pages. *

* * @return a list of references to visible views */ virtual QList GetViewReferences() = 0; /** * Returns a list of the views visible on this page. *

* Note that each page has its own views; views are never shared between * pages. *

* * @return a list of visible views * * @deprecated use #getViewReferences() instead. */ virtual QList GetViews() = 0; /** * Returns the workbench window of this page. * * @return the workbench window */ virtual IWorkbenchWindow::Pointer GetWorkbenchWindow() = 0; /** * Hides the given view. The view must belong to this page. * * @param view * the view to hide */ virtual void HideView(IViewPart::Pointer view) = 0; /** * Hides the given view that belongs to the reference, if any. * * @param view * the references whos view is to be hidden */ virtual void HideView(IViewReference::Pointer view) = 0; /** * Returns true if perspective with given id contains view with given id */ - virtual bool HasView(const std::string& perspectiveId, const std::string& viewId) = 0; + virtual bool HasView(const QString& perspectiveId, const QString& viewId) = 0; /** * Returns whether the specified part is visible. * * @param part * the part to test * @return boolean true if part is visible */ virtual bool IsPartVisible(IWorkbenchPart::Pointer part) = 0; /** * Removes the perspective specified by desc. * * @param desc * the perspective that will be removed */ virtual void RemovePerspective(IPerspectiveDescriptor::Pointer desc) = 0; /** * Reuses the specified editor by setting its new input. * * @param editor * the editor to be reused * @param input * the new input for the reusable editor */ virtual void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open on the target input that editor * is activated; otherwise, a new editor is opened. Two editor inputs, * input1 and input2, are considered the same if * *

    * input1.equals(input2) == true
    * 
. *

*

* The editor type is determined by mapping editorId to an * editor extension registered with the workbench. An editor id is passed * rather than an editor object to prevent the accidental creation of more * than one editor for the same input. It also guarantees a consistent * lifecycle for editors, regardless of whether they are created by the user * or restored from saved data. *

* * @param input * the editor input * @param editorId * the id of the editor extension to use * @return an open and active editor, or null if an external * editor was opened * @exception PartInitException * if the editor could not be created or initialized */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open on the target input that editor * is brought to the front; otherwise, a new editor is opened. Two editor * inputs are considered the same if they equal. See * Object.equals(Object) * and IEditorInput. If activate == true the editor * will be activated. *

* The editor type is determined by mapping editorId to an editor * extension registered with the workbench. An editor id is passed rather than * an editor object to prevent the accidental creation of more than one editor * for the same input. It also guarantees a consistent lifecycle for editors, * regardless of whether they are created by the user or restored from saved * data. *

* * @param input the editor input * @param editorId the id of the editor extension to use * @param activate if true the editor will be activated * @return an open editor, or null if an external editor was opened * @exception PartInitException if the editor could not be created or initialized */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId, bool activate) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open that matches the given input * and/or editor id (as specified by the matchFlags argument), that editor * is brought to the front; otherwise, a new editor is opened. Two editor * inputs are considered the same if they equal. See * Object.equals(Object) * and IEditorInput. If activate == true the editor * will be activated. *

* The editor type is determined by mapping editorId to an editor * extension registered with the workbench. An editor id is passed rather than * an editor object to prevent the accidental creation of more than one editor * for the same input. It also guarantees a consistent lifecycle for editors, * regardless of whether they are created by the user or restored from saved * data. *

* * @param input the editor input * @param editorId the id of the editor extension to use * @param activate if true the editor will be activated * @param matchFlags a bit mask consisting of zero or more of the MATCH_* constants OR-ed together * @return an open editor, or null if an external editor was opened * @exception PartInitException if the editor could not be created or initialized * * @see #MATCH_NONE * @see #MATCH_INPUT * @see #MATCH_ID */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId, bool activate, int matchFlags) = 0; /** * Removes the property change listener. * * @param listener * the property change listener to remove */ //virtual void removePropertyChangeListener(IPropertyChangeListener listener); /** * Changes the visible views, their layout, and the visible action sets * within the page to match the current perspective descriptor. This is a * rearrangement of components and not a replacement. The contents of the * current perspective descriptor are unaffected. *

* For more information on perspective change see * setPerspective(). *

*/ virtual void ResetPerspective() = 0; /** * Saves the contents of all dirty editors belonging to this workbench page. * If there are no dirty editors this method returns without effect. *

* If confirm is true the user is prompted to * confirm the command. *

*

* Note that as of 3.2, this method also saves views that implement * ISaveablePart and are dirty. *

* * @param confirm true to ask the user before saving unsaved * changes (recommended), and false to save * unsaved changes without asking * @return true if the command succeeded, and * false if the operation was canceled by the user or * an error occurred while saving */ virtual bool SaveAllEditors(bool confirm) = 0; /** * Saves the contents of the given editor if dirty. If not, this method * returns without effect. *

* If confirm is true the user is prompted to * confirm the command. Otherwise, the save happens without prompt. *

*

* The editor must belong to this workbench page. *

* * @param editor * the editor to close * @param confirm * true to ask the user before saving unsaved * changes (recommended), and false to save * unsaved changes without asking * @return true if the command succeeded, and * false if the editor was not saved */ virtual bool SaveEditor(IEditorPart::Pointer editor, bool confirm) = 0; /** * Saves the visible views, their layout, and the visible action sets for * this page to the current perspective descriptor. The contents of the * current perspective descriptor are overwritten. */ virtual void SavePerspective() = 0; /** * Saves the visible views, their layout, and the visible action sets for * this page to the given perspective descriptor. The contents of the given * perspective descriptor are overwritten and it is made the current one for * this page. * * @param perspective * the perspective descriptor to save to */ virtual void SavePerspectiveAs(IPerspectiveDescriptor::Pointer perspective) = 0; /** * Changes the visible views, their layout, and the visible action sets * within the page to match the given perspective descriptor. This is a * rearrangement of components and not a replacement. The contents of the * old perspective descriptor are unaffected. *

* When a perspective change occurs the old perspective is deactivated * (hidden) and cached for future reference. Then the new perspective is * activated (shown). The views within the page are shared by all existing * perspectives to make it easy for the user to switch between one * perspective and another quickly without loss of context. *

*

* During activation the action sets are modified. If an action set is * specified in the new perspective which is not visible in the old one it * will be created. If an old action set is not specified in the new * perspective it will be disposed. *

*

* The visible views and their layout within the page also change. If a view * is specified in the new perspective which is not visible in the old one a * new instance of the view will be created. If an old view is not specified * in the new perspective it will be hidden. This view may reappear if the * user selects it from the View menu or if they switch to a perspective * (which may be the old one) where the view is visible. *

*

* The open editors are not modified by this method. *

* * @param perspective * the perspective descriptor */ virtual void SetPerspective(IPerspectiveDescriptor::Pointer perspective) = 0; /** * Shows the view identified by the given view id in this page and gives it * focus. If there is a view identified by the given view id (and with no * secondary id) already open in this page, it is given focus. * * @param viewId * the id of the view extension to use * @return the shown view * @exception PartInitException * if the view could not be initialized */ virtual IViewPart::Pointer ShowView(const QString& viewId) = 0; /** * Shows a view in this page with the given id and secondary id. The * behaviour of this method varies based on the supplied mode. If * VIEW_ACTIVATE is supplied, the view is focus. If * VIEW_VISIBLE is supplied, then it is made visible but not * given focus. Finally, if VIEW_CREATE is supplied the view * is created and will only be made visible if it is not created in a folder * that already contains visible views. *

* This allows multiple instances of a particular view to be created. They * are disambiguated using the secondary id. If a secondary id is given, the * view must allow multiple instances by having specified * allowMultiple="true" in its extension. *

* * @param viewId * the id of the view extension to use * @param secondaryId * the secondary id to use, or null for no * secondary id * @param mode * the activation mode. Must be {@link #VIEW_ACTIVATE}, * {@link #VIEW_VISIBLE} or {@link #VIEW_CREATE} * @return a view * @exception PartInitException * if the view could not be initialized * @exception IllegalArgumentException * if the supplied mode is not valid */ virtual IViewPart::Pointer ShowView(const QString& viewId, const QString& secondaryId, int mode) = 0; /** * Returns true if the editor is pinned and should not be * reused. * * @param editor * the editor to test * @return boolean whether the editor is pinned */ virtual bool IsEditorPinned(IEditorPart::Pointer editor) = 0; /** * Returns the perspective shortcuts associated with the current * perspective. Returns an empty array if there is no current perspective. * * @see IPageLayout#addPerspectiveShortcut(String) * @return an array of perspective identifiers */ virtual QList GetPerspectiveShortcuts() = 0; /** * Returns the show view shortcuts associated with the current perspective. * Returns an empty array if there is no current perspective. * * @see IPageLayout#addShowViewShortcut(String) * @return an array of view identifiers */ virtual QList GetShowViewShortcuts() = 0; /** * Returns the descriptors for the perspectives that are open in this page, * in the order in which they were opened. * * @return the open perspective descriptors, in order of opening */ virtual QList GetOpenPerspectives() = 0; /** * Returns the descriptors for the perspectives that are open in this page, * in the order in which they were activated (oldest first). * * @return the open perspective descriptors, in order of activation */ virtual QList GetSortedPerspectives() = 0; /** * Closes current perspective. If last perspective, then entire page * is closed. * * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ virtual void CloseCurrentPerspective(bool saveParts, bool closePage) = 0; /** * Closes the specified perspective in this page. If the last perspective in * this page is closed, then all editors are closed. Views that are not * shown in other perspectives are closed as well. If saveParts * is true, the user will be prompted to save any unsaved * changes for parts that are being closed. The page itself is closed if * closePage is true. * * @param desc * the descriptor of the perspective to be closed * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ virtual void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) = 0; /** * Closes all perspectives in this page. All editors are closed, prompting * to save any unsaved changes if saveEditors is * true. The page itself is closed if closePage * is true. * * @param saveEditors * whether the page's editors should be saved * @param closePage * whether the page itself should be closed */ virtual void CloseAllPerspectives(bool saveEditors, bool closePage) = 0; /** * Find the part reference for the given part. A convenience method to * quickly go from part to part reference. * * @param part * The part to search for. It can be null. * @return The reference for the given part, or null if no * reference can be found. */ virtual IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part) = 0; }; } // namespace berry #endif /*BERRYIWORKBENCHPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h index 16e689863e..5c21b6ff59 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h @@ -1,213 +1,213 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIWORKBENCHWINDOW_H_ #define BERRYIWORKBENCHWINDOW_H_ #include #include #include #include "berryIPageService.h" #include "berryShell.h" #include "services/berryIServiceLocator.h" namespace berry { struct IPartService; struct ISelectionService; struct IWorkbenchPage; struct IWorkbench; /** * \ingroup org_blueberry_ui_qt * * A workbench window is a top level window in a workbench. Visually, a * workbench window has a menubar, a toolbar, a status bar, and a main area for * displaying a single page consisting of a collection of views and editors. *

* Each workbench window has a collection of 0 or more pages; the active page is * the one that is being presented to the end user; at most one page is active * in a window at a time. *

*

* The workbench window supports a few {@link IServiceLocator services} by * default. If these services are used to allocate resources, it is important to * remember to clean up those resources after you are done with them. Otherwise, * the resources will exist until the workbench window is closed. The supported * services are: *

*
    *
  • {@link ICommandService}
  • *
  • {@link IContextService}
  • *
  • {@link IHandlerService}
  • *
  • {@link IBindingService}. Resources allocated through this service will * not be cleaned up until the workbench shuts down.
  • *
*

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

* * @see IWorkbenchPage * @noimplement This interface is not intended to be implemented by clients. * */ struct BERRY_UI_QT IWorkbenchWindow : public IPageService, public IServiceLocator, public virtual Object { berryObjectMacro(berry::IWorkbenchWindow) /** * Closes this workbench window. *

* If the window has an open editor with unsaved content, the user will be * given the opportunity to save it. *

* * @return true if the window was successfully closed, and * false if it is still open */ virtual bool Close() = 0; - virtual SmartPointer GetPage(int i) = 0; + virtual SmartPointer GetPage(int i) const = 0; /** * Returns the currently active page for this workbench window. * * @return the active page, or null if none */ virtual SmartPointer GetActivePage() const = 0; /** * Sets or clears the currently active page for this workbench window. * * @param page * the new active page */ virtual void SetActivePage(SmartPointer page) = 0; /** * Returns the part service which tracks part activation within this * workbench window. * * @return the part service */ virtual IPartService* GetPartService() = 0; /** * Returns the selection service which tracks selection within this * workbench window. * * @return the selection service */ virtual ISelectionService* GetSelectionService() = 0; /** * Returns this workbench window's shell. * * @return the shell containing this window's controls or null * if the shell has not been created yet or if the window has been closed */ virtual Shell::Pointer GetShell() const = 0; /** * Returns the workbench for this window. * * @return the workbench */ virtual IWorkbench* GetWorkbench() = 0; /** * Returns whether the specified menu is an application menu as opposed to * a part menu. Application menus contain items which affect the workbench * or window. Part menus contain items which affect the active part (view * or editor). *

* This is typically used during "in place" editing. Application menus * should be preserved during menu merging. All other menus may be removed * from the window. *

* * @param menuId * the menu id * @return true if the specified menu is an application * menu, and false if it is not */ //virtual bool IsApplicationMenu(const QString& menuId) = 0; /** * Creates and opens a new workbench page. The perspective of the new page * is defined by the specified perspective ID. The new page become active. *

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

* * @param perspectiveId * the perspective id for the window's initial page * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench page * @exception WorkbenchException * if a page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual SmartPointer OpenPage(const QString& perspectiveId, IAdaptable* input) = 0; /** * Creates and opens a new workbench page. The default perspective is used * as a template for creating the page. The page becomes active. *

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

* * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench window * @exception WorkbenchException * if a page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual SmartPointer OpenPage(IAdaptable* input) = 0; - virtual void SetPerspectiveExcludeList(std::vector v) = 0; - virtual std::vector GetPerspectiveExcludeList() = 0; + virtual void SetPerspectiveExcludeList(const QStringList& v) = 0; + virtual QStringList GetPerspectiveExcludeList() const = 0; - virtual void SetViewExcludeList(std::vector v) = 0; - virtual std::vector GetViewExcludeList() = 0; + virtual void SetViewExcludeList(const QStringList& v) = 0; + virtual QStringList GetViewExcludeList() const = 0; virtual ~IWorkbenchWindow(); }; } #endif /*BERRYIWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp index f83af8992f..7ec7694dd2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp @@ -1,1811 +1,1811 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveExtensionReader.h" #include "berryEditorSashContainer.h" #include "berryPartSite.h" #include "berryViewSite.h" #include "berryEditorAreaHelper.h" #include "intro/berryIntroConstants.h" #include "dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" #include "berryStatusUtil.h" #include "presentations/berryIStackPresentationSite.h" namespace berry { const QString Perspective::VERSION_STRING = "0.016"; Perspective::Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page) : descriptor(desc) { this->Init(page); if (desc.IsNotNull()) { this->CreatePresentation(desc); } } Perspective::Perspective(WorkbenchPage::Pointer page) { this->Init(page); } void Perspective::Init(WorkbenchPage::Pointer page) { editorHidden = false; editorAreaState = IStackPresentationSite::STATE_RESTORED; fixed = false; presentation = 0; shouldHideEditorsOnActivate = false; this->page = page.GetPointer(); this->editorArea = page->GetEditorPresentation()->GetLayoutPart(); this->viewFactory = page->GetViewFactory(); } bool Perspective::BringToTop(IViewReference::Pointer ref) { return presentation->BringPartToTop(this->GetPane(ref)); } bool Perspective::ContainsView(IViewPart::Pointer view) { IViewSite::Pointer site = view->GetViewSite(); IViewReference::Pointer ref = this->FindView(site->GetId(), site->GetSecondaryId()); if (ref.IsNull()) { return false; } return (view.Cast() == ref->GetPart(false)); } -bool Perspective::ContainsView(const std::string& viewId) +bool Perspective::ContainsView(const QString& viewId) const { return mapIDtoViewLayoutRec.contains(viewId); } void Perspective::CreatePresentation(PerspectiveDescriptor::Pointer persp) { if (persp->HasCustomDefinition()) { this->LoadCustomPersp(persp); } else { this->LoadPredefinedPersp(persp); } } Perspective::~Perspective() { // Get rid of presentation. if (presentation == 0) { DisposeViewRefs(); return; } presentation->Deactivate(); // Release each view. QList refs(this->GetViewReferences()); for (QList::size_type i = 0, length = refs.size(); i < length; i++) { this->GetViewFactory()->ReleaseView(refs[i]); } mapIDtoViewLayoutRec.clear(); delete presentation; } void Perspective::DisposeViewRefs() { if (!memento) { return; } QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId = ViewFactory::ExtractSecondaryId(id); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } QString removed; childMem->GetString(WorkbenchConstants::TAG_REMOVED, removed); if (removed != "true") { IViewReference::Pointer ref = viewFactory->GetView(id, secondaryId); if (ref) { viewFactory->ReleaseView(ref); } } } } IViewReference::Pointer Perspective::FindView(const QString& viewId) { return this->FindView(viewId, ""); } IViewReference::Pointer Perspective::FindView(const QString& id, const QString& secondaryId) { QList refs(this->GetViewReferences()); for (int i = 0; i < refs.size(); i++) { IViewReference::Pointer ref = refs[i]; if (id == ref->GetId() && (secondaryId == ref->GetSecondaryId())) { return ref; } } return IViewReference::Pointer(0); } void* Perspective::GetClientComposite() { return page->GetClientComposite(); } IPerspectiveDescriptor::Pointer Perspective::GetDesc() { return descriptor; } PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref) { return ref.Cast()->GetPane(); } QList Perspective::GetPerspectiveShortcuts() { return perspectiveShortcuts; } PerspectiveHelper* Perspective::GetPresentation() const { return presentation; } QList Perspective::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* Perspective::GetViewFactory() { return viewFactory; } QList Perspective::GetViewReferences() { // Get normal views. if (presentation == 0) { return QList(); } QList panes; presentation->CollectViewPanes(panes); QList result; // List fastViews = (fastViewManager != 0) ? // fastViewManager.getFastViews(0) // : new ArrayList(); // IViewReference[] resultArray = new IViewReference[panes.size() // + fastViews.size()]; // // // Copy fast views. // int nView = 0; // for (int i = 0; i < fastViews.size(); i++) // { // resultArray[nView] = (IViewReference) fastViews.get(i); // ++nView; // } // Copy normal views. for (QList::iterator iter = panes.begin(); iter != panes.end(); ++iter) { PartPane::Pointer pane = *iter; result.push_back(pane->GetPartReference().Cast()); } return result; } void Perspective::HideEditorArea() { if (!this->IsEditorAreaVisible()) { return; } // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { // If it's the currently maximized part we have to restore first // if (this->GetPresentation().getMaximizedStack().Cast() != 0) // { // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) this->HideEditorAreaLocal(); //else // this->SetEditorAreaTrimVisibility(false); } else { this->HideEditorAreaLocal(); } editorHidden = true; } void Perspective::HideEditorAreaLocal() { if (editorHolder != 0) { return; } // Replace the editor area with a placeholder so we // know where to put it back on show editor area request. editorHolder = new PartPlaceholder(editorArea->GetID()); presentation->GetLayout()->Replace(editorArea, editorHolder); } bool Perspective::HideView(IViewReference::Pointer ref) { // If the view is locked just return. PartPane::Pointer pane = this->GetPane(ref); presentation->RemovePart(pane); // Dispose view if ref count == 0. this->GetViewFactory()->ReleaseView(ref); return true; } bool Perspective::IsEditorAreaVisible() { return !editorHidden; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(IViewReference::Pointer ref, bool create) { ViewLayoutRec::Pointer result = this->GetViewLayoutRec(ViewFactory::GetKey(ref), create); if (result.IsNull() && create==false) { result = this->GetViewLayoutRec(ref->GetId(), false); } return result; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(const QString& viewId, bool create) { ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[viewId]; if (rec.IsNull() && create) { rec = new ViewLayoutRec(); mapIDtoViewLayoutRec[viewId] = rec; } return rec; } bool Perspective::IsFixedLayout() { //@issue is there a difference between a fixed //layout and a fixed perspective?? If not the API //may need some polish, WorkbenchPage, PageLayout //and Perspective all have isFixed methods. //PageLayout and Perspective have their own fixed //attribute, we are assuming they are always in sync. //WorkbenchPage delegates to the perspective. return fixed; } bool Perspective::IsStandaloneView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->isStandalone; } bool Perspective::GetShowTitleView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->showTitle; } void Perspective::LoadCustomPersp(PerspectiveDescriptor::Pointer persp) { //get the layout from the registry PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); try { IMemento::Pointer memento = perspRegistry->GetCustomPersp(persp->GetId()); // Restore the layout state. // MultiStatus status = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()), // 0); // status.merge(restoreState(memento)); // status.merge(restoreState()); bool okay = true; okay &= this->RestoreState(memento); okay &= this->RestoreState(); if (!okay) { this->UnableToOpenPerspective(persp, "Unable to open perspective: " + persp->GetLabel()); } } //catch (IOException e) //{ // unableToOpenPerspective(persp, 0); //} catch (const WorkbenchException& e) { this->UnableToOpenPerspective(persp, e.what()); } } void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status) { PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin ::GetDefault()->GetPerspectiveRegistry()); perspRegistry->DeletePerspective(persp); // If this is a predefined perspective, we will not be able to delete // the perspective (we wouldn't want to). But make sure to delete the // customized portion. persp->DeleteCustomDefinition(); QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; if (status == "") { MessageDialog::OpenError(Shell::Pointer(0), title, msg); } else { //TODO error dialog //ErrorDialog.openError((Shell) 0, title, msg, status); MessageDialog::OpenError(Shell::Pointer(0), title, msg + "\n" + status); } } void Perspective::LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp) { // Create layout engine. IPerspectiveFactory::Pointer factory; try { factory = persp->CreateFactory(); } catch (CoreException& /*e*/) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } /* * IPerspectiveFactory#createFactory() can return 0 */ if (factory == 0) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } // Create layout factory. ViewSashContainer::Pointer container(new ViewSashContainer(page, this->GetClientComposite())); layout = new PageLayout(container, this->GetViewFactory(), editorArea, descriptor); layout->SetFixed(descriptor->GetFixed()); // // add the placeholders for the sticky folders and their contents IPlaceholderFolderLayout::Pointer stickyFolderRight, stickyFolderLeft, stickyFolderTop, stickyFolderBottom; QList descs(WorkbenchPlugin::GetDefault() ->GetViewRegistry()->GetStickyViews()); for (int i = 0; i < descs.size(); i++) { IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i]; QString id = stickyViewDescriptor->GetId(); int location = stickyViewDescriptor->GetLocation(); if (location == IPageLayout::RIGHT) { if (stickyFolderRight == 0) { stickyFolderRight = layout ->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_RIGHT, IPageLayout::RIGHT, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderRight->AddPlaceholder(id); } else if (location == IPageLayout::LEFT) { if (stickyFolderLeft == 0) { stickyFolderLeft = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_LEFT, IPageLayout::LEFT, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderLeft->AddPlaceholder(id); } else if (location == IPageLayout::TOP) { if (stickyFolderTop == 0) { stickyFolderTop = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_TOP, IPageLayout::TOP, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderTop->AddPlaceholder(id); } else if (location == IPageLayout::BOTTOM) { if (stickyFolderBottom == 0) { stickyFolderBottom = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_BOTTOM, IPageLayout::BOTTOM, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderBottom->AddPlaceholder(id); } //should never be 0 as we've just added the view above IViewLayout::Pointer viewLayout = layout->GetViewLayout(id); viewLayout->SetCloseable(stickyViewDescriptor->IsCloseable()); viewLayout->SetMoveable(stickyViewDescriptor->IsMoveable()); } // Run layout engine. factory->CreateInitialLayout(layout); PerspectiveExtensionReader extender; extender.ExtendLayout(descriptor->GetId(), layout); // Retrieve view layout info stored in the page layout. QHash layoutInfo = layout->GetIDtoViewLayoutRecMap(); mapIDtoViewLayoutRec.unite(layoutInfo); //TODO Perspective action sets // Create action sets. //List temp = new ArrayList(); //this->CreateInitialActionSets(temp, layout.getActionSets()); // IContextService service = 0; // if (page != 0) // { // service = (IContextService) page.getWorkbenchWindow().getService( // IContextService.class); // } // try // { // if (service!=0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // for (Iterator iter = temp.iterator(); iter.hasNext();) // { // IActionSetDescriptor descriptor = (IActionSetDescriptor) iter // .next(); // addAlwaysOn(descriptor); // } // }finally // { // if (service!=0) // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // newWizardShortcuts = layout.getNewWizardShortcuts(); showViewShortcuts = layout->GetShowViewShortcuts(); // perspectiveShortcuts = layout.getPerspectiveShortcuts(); // showInPartIds = layout.getShowInPartIds(); // // // Retrieve fast views // if (fastViewManager != 0) // { // ArrayList fastViews = layout.getFastViews(); // for (Iterator fvIter = fastViews.iterator(); fvIter.hasNext();) // { // IViewReference ref = (IViewReference) fvIter.next(); // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, // !fvIter.hasNext()); // } // } // Is the layout fixed fixed = layout->IsFixed(); showViewShortcuts = layout->GetShowViewShortcuts(); // Create presentation. presentation = new PerspectiveHelper(page, container, this); // Hide editor area if requested by factory if (!layout->IsEditorAreaVisible()) { this->HideEditorArea(); } } void Perspective::OnActivate() { // Update editor area state. if (editorArea->GetControl() != 0) { bool visible = this->IsEditorAreaVisible(); bool inTrim = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; editorArea->SetVisible(visible && !inTrim); } // // Update fast views. // // Make sure the control for the fastviews are created so they can // // be activated. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl == 0) // { // pane.createControl(getClientComposite()); // ctrl = pane.getControl(); // } // ctrl.setEnabled(false); // Remove focus support. // } // } // } // // Set the visibility of all fast view pins // setAllPinsVisible(true); // Trim Stack Support bool useNewMinMax = Perspective::UseNewMinMax(Perspective::Pointer(this)); bool hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == 0); // We have to set the editor area's stack state -before- // activating the presentation since it's used there to determine // size of the resulting stack if (useNewMinMax && !hideEditorArea) { this->RefreshEditorAreaVisibility(); } // Show the layout presentation->Activate(this->GetClientComposite()); // if (useNewMinMax) // { // fastViewManager.activate(); // // // Move any minimized extension stacks to the trim // if (layout != 0) // { // // Turn aimations off // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useAnimations = preferenceStore // .getbool(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS); // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false); // // List minStacks = layout.getMinimizedStacks(); // for (Iterator msIter = minStacks.iterator(); msIter.hasNext();) // { // ViewStack vs = (ViewStack) msIter.next(); // vs.setMinimized(true); // } // // // Restore the animation pref // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations); // // // this is a one-off deal...set during the extension reading // minStacks.clear(); // layout = 0; // } // } // else // { // // Update the FVB only if not using the new min/max // // // WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow(); //// if (wbw != 0) //// { //// ITrimManager tbm = wbw.getTrimManager(); //// if (tbm != 0) //// { //// IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID); //// if (fvb instanceof FastViewBar) //// { //// ((FastViewBar)fvb).update(true); //// } //// } //// } // } // // If we are -not- using the new min/max then ensure that there // // are no stacks in the trim. This can happen when a user switches // // back to the 3.0 presentation... // if (!Perspective.useNewMinMax(this) && fastViewManager != 0) // { // bool stacksWereRestored = fastViewManager.restoreAllTrimStacks(); // setEditorAreaTrimVisibility(false); // // // Restore any 'maximized' view stack since we've restored // // the minimized stacks // if (stacksWereRestored && presentation.getMaximizedStack().Cast() != 0) // { // ViewStack vs = (ViewStack) presentation.getMaximizedStack(); // vs.setPresentationState(IStackPresentationSite.STATE_RESTORED); // presentation.setMaximizedStack(0); // } // } // We hide the editor area -after- the presentation activates if (hideEditorArea) { // We do this here to ensure that createPartControl is called on the // top editor // before it is hidden. See bug 20166. this->HideEditorArea(); shouldHideEditorsOnActivate = false; // // this is an override so it should handle both states // if (useNewMinMax) // setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED); } FixOrphan(); } void Perspective::FixOrphan() { PerspectiveRegistry* reg = static_cast(PlatformUI::GetWorkbench()->GetPerspectiveRegistry()); IPerspectiveDescriptor::Pointer regDesc = reg->FindPerspectiveWithId(descriptor->GetId()); if (regDesc.IsNull()) { QString msg = "Perspective " + descriptor->GetLabel() + " has been made into a local copy"; IStatus::Pointer status = StatusUtil::NewStatus(IStatus::WARNING_TYPE, msg, BERRY_STATUS_LOC); //StatusManager.getManager().handle(status, StatusManager.LOG); WorkbenchPlugin::Log(status); QString localCopyLabel("<%1>"); QString newDescId = localCopyLabel.arg(descriptor->GetLabel()); while (reg->FindPerspectiveWithId(newDescId).IsNotNull()) { newDescId = localCopyLabel.arg(newDescId); } - PerspectiveDescriptor::Pointer newDesc = reg->CreatePerspective(newDescId, descriptor); + IPerspectiveDescriptor::Pointer newDesc = reg->CreatePerspective(newDescId, descriptor); page->SavePerspectiveAs(newDesc); } } void Perspective::OnDeactivate() { presentation->Deactivate(); //setActiveFastView(0); //setAllPinsVisible(false); // // Update fast views. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl != 0) // { // ctrl.setEnabled(true); // Add focus support. // } // } // } // // fastViewManager.deActivate(); // } // // // Ensure that the editor area trim is hidden as well // setEditorAreaTrimVisibility(false); } void Perspective::PartActivated(IWorkbenchPart::Pointer /*activePart*/) { // // If a fastview is open close it. // if (activeFastView != 0 // && activeFastView.getPart(false) != activePart) // { // setActiveFastView(0); // } } void Perspective::PerformedShowIn(const QString& /*partId*/) { //showInTimes.insert(std::make_pair(partId, new Long(System.currentTimeMillis()))); } bool Perspective::RestoreState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; // Create persp descriptor. descriptor = new PerspectiveDescriptor("", "", PerspectiveDescriptor::Pointer(0)); //result.add(descriptor.restoreState(memento)); result &= descriptor->RestoreState(memento); PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->FindPerspectiveWithId(descriptor->GetId()).Cast(); if (desc) { descriptor = desc; } else { try { WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->CreatePerspective(descriptor->GetLabel(), descriptor.Cast()); } catch (...) { std::cout << "Perspective could not be loaded" << std::endl; } } this->memento = memento; // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); //result.merge(createReferences(views)); result &= this->CreateReferences(views); memento = memento->GetChild(WorkbenchConstants::TAG_FAST_VIEWS); if (memento) { views = memento->GetChildren(WorkbenchConstants::TAG_VIEW); //result.merge(createReferences(views)); result &= this->CreateReferences(views); } return result; } bool Perspective::CreateReferences(const QList& views) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringViews, 0); bool result = true; for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // Create and open the view. try { QString rm; childMem->GetString(WorkbenchConstants::TAG_REMOVED, rm); if (rm != "true") { viewFactory->CreateView(id, secondaryId); } } catch (const PartInitException& e) { childMem->PutString(WorkbenchConstants::TAG_REMOVED, "true"); // result.add(StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e)); WorkbenchPlugin::Log(e.what(), e); result &= true; } } return result; } bool Perspective::RestoreState() { if (this->memento == 0) { //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; IMemento::Pointer memento = this->memento; this->memento = 0; const IMemento::Pointer boundsMem(memento->GetChild(WorkbenchConstants::TAG_WINDOW)); if (boundsMem) { Rectangle r(0, 0, 0, 0); boundsMem->GetInteger(WorkbenchConstants::TAG_X, r.x); boundsMem->GetInteger(WorkbenchConstants::TAG_Y, r.y); boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, r.height); boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, r.width); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { if (page->GetWorkbenchWindow()->GetActivePage() == 0) { page->GetWorkbenchWindow()->GetShell()->SetBounds(r); } // } // }); } // Create an empty presentation.. PerspectiveHelper* pres; //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { ViewSashContainer::Pointer mainLayout(new ViewSashContainer(page, this->GetClientComposite())); pres = new PerspectiveHelper(page, mainLayout, this); // }}); // Read the layout. // result.merge(pres.restoreState(memento // .getChild(IWorkbenchConstants.TAG_LAYOUT))); result &= pres->RestoreState(memento->GetChild(WorkbenchConstants::TAG_LAYOUT)); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // Add the editor workbook. Do not hide it now. pres->ReplacePlaceholderWithPart(editorArea); // }}); // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // skip the intro as it is restored higher up in workbench. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } // Create and open the view. IViewReference::Pointer viewRef = viewFactory->GetView(id, secondaryId); WorkbenchPartReference::Pointer ref = viewRef.Cast(); // report error if (ref == 0) { QString key = ViewFactory::GetKey(id, secondaryId); // result.add(new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, // NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), 0)); WorkbenchPlugin::Log("Could not find view: " + key); continue; } bool willPartBeVisible = pres->WillPartBeVisible(ref->GetId(), secondaryId); if (willPartBeVisible) { IViewPart::Pointer view = ref->GetPart(true).Cast(); if (view) { ViewSite::Pointer site = view->GetSite().Cast(); pres->ReplacePlaceholderWithPart(site->GetPane().Cast()); } } else { pres->ReplacePlaceholderWithPart(ref->GetPane()); } } // // Load the fast views // if (fastViewManager != 0) // fastViewManager.restoreState(memento, result); // Load the view layout recs QList recMementos(memento ->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); for (int i = 0; i < recMementos.size(); i++) { IMemento::Pointer recMemento = recMementos[i]; QString compoundId; if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId)) { ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true); QString closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr); if (WorkbenchConstants::FALSE_VAL == closeablestr) { rec->isCloseable = false; } QString moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr); if (WorkbenchConstants::FALSE_VAL == moveablestr) { rec->isMoveable = false; } QString standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr); if (WorkbenchConstants::TRUE_VAL == standalonestr) { rec->isStandalone = true; QString showstr; recMemento->GetString(WorkbenchConstants::TAG_SHOW_TITLE, showstr); rec->showTitle = WorkbenchConstants::FALSE_VAL != showstr; } } } //final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); try { // one big try block, don't kill me here // // defer context events // if (service != 0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // // HashSet knownActionSetIds = new HashSet(); // // // Load the always on action sets. QList actions; // = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // // knownActionSetIds.add(actionSetID); // } // } // // // Load the always off action sets. // actions = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOff(d); // } // }); // knownActionSetIds.add(actionSetID); // } // } // Load "show view actions". actions = memento->GetChildren(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); showViewShortcuts.push_back(id); } // // Load "show in times". // actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // String timeStr = actions[x] // .getString(IWorkbenchConstants.TAG_TIME); // if (id != 0 && timeStr != 0) // { // try // { // long time = Long.parseLong(timeStr); // showInTimes.put(id, new Long(time)); // } // catch (NumberFormatException e) // { // // skip this one // } // } // } // Load "show in parts" from registry, not memento showInPartIds = this->GetShowInIdsFromRegistry(); // // Load "new wizard actions". // actions = memento // .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // newWizardShortcuts = new ArrayList(actions.length); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // newWizardShortcuts.add(id); // } // Load "perspective actions". actions = memento->GetChildren(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); perspectiveShortcuts.push_back(id); } // ArrayList extActionSets = getPerspectiveExtensionActionSets(); // for (int i = 0; i < extActionSets.size(); i++) // { // String actionSetID = (String) extActionSets.get(i); // if (knownActionSetIds.contains(actionSetID)) // { // continue; // } // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // knownActionSetIds.add(d.getId()); // } // } // // Add the visible set of action sets to our knownActionSetIds // // Now go through the registry to ensure we pick up any new action // // sets // // that have been added but not yet considered by this perspective. // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // IActionSetDescriptor[] array = reg.getActionSets(); // int count = array.length; // for (int i = 0; i < count; i++) // { // IActionSetDescriptor desc = array[i]; // if ((!knownActionSetIds.contains(desc.getId())) // && (desc.isInitiallyVisible())) // { // addActionSet(desc); // } // } } catch (...) { // // restart context changes // if (service != 0) // { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // }); // } } // Save presentation. presentation = pres; // Hide the editor area if needed. Need to wait for the // presentation to be fully setup first. int areaVisible = 0; bool areaVisibleExists = memento->GetInteger(WorkbenchConstants::TAG_AREA_VISIBLE, areaVisible); // Rather than hiding the editors now we must wait until after their // controls // are created. This ensures that if an editor is instantiated, // createPartControl // is also called. See bug 20166. shouldHideEditorsOnActivate = (areaVisibleExists && areaVisible == 0); // // Restore the trim state of the editor area // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // Integer trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE); // if (trimStateInt != 0) // { // editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state // editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0; // } // } // restore the fixed state int isFixed = 0; fixed = (memento->GetInteger(WorkbenchConstants::TAG_FIXED, isFixed) && isFixed == 1); return true; } QList Perspective::GetShowInIdsFromRegistry() { PerspectiveExtensionReader reader; QList tags; tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART); reader.SetIncludeOnlyTags(tags); PageLayout::Pointer layout(new PageLayout()); reader.ExtendLayout(descriptor->GetOriginalId(), layout); return layout->GetShowInPartIds(); } void Perspective::SaveDesc() { this->SaveDescAs(descriptor); } void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer /*desc*/) { //TODO Perspective SaveDescAs // PerspectiveDescriptor::Pointer realDesc = desc.Cast(); // //get the layout from the registry // PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin // ::GetDefault()->GetPerspectiveRegistry()); // // Capture the layout state. // XMLMemento memento = XMLMemento.createWriteRoot("perspective");//$NON-NLS-1$ // IStatus status = saveState(memento, realDesc, false); // if (status.getSeverity() == IStatus.ERR) // { // ErrorDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage, // status); // return; // } // //save it to the preference store // try // { // perspRegistry.saveCustomPersp(realDesc, memento); // descriptor = realDesc; // } // catch (IOException e) // { // perspRegistry.deletePerspective(realDesc); // MessageDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage); // } } bool Perspective::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); // // result.merge(saveState(memento, descriptor, true)); bool result = true; result &= this->SaveState(memento, descriptor, true); return result; } bool Perspective::SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); bool result = true; if (this->memento) { memento->PutMemento(this->memento); return result; } // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING); //result.add(p.saveState(memento)); result &= p->SaveState(memento); if (!saveInnerViewState) { Rectangle bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds()); IMemento::Pointer boundsMem = memento ->CreateChild(WorkbenchConstants::TAG_WINDOW); boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x); boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); } // // Save the "always on" action sets. // Iterator itr = alwaysOnActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // // Save the "always off" action sets. // itr = alwaysOffActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // Save "show view actions" for (QList::iterator itr = showViewShortcuts.begin(); itr != showViewShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // // Save "show in times" // itr = showInTimes.keySet().iterator(); // while (itr.hasNext()) // { // String id = (String) itr.next(); // Long time = (Long) showInTimes.get(id); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME); // child.putString(IWorkbenchConstants.TAG_ID, id); // child.putString(IWorkbenchConstants.TAG_TIME, time.toString()); // } // // Save "new wizard actions". // itr = newWizardShortcuts.iterator(); // while (itr.hasNext()) // { // String str = (String) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // child.putString(IWorkbenchConstants.TAG_ID, str); // } // Save "perspective actions". for (QList::iterator itr = perspectiveShortcuts.begin(); itr != perspectiveShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // Get visible views. QList viewPanes; presentation->CollectViewPanes(viewPanes); // Save the views. for (QList::iterator itr = viewPanes.begin(); itr != viewPanes.end(); ++itr) { IWorkbenchPartReference::Pointer ref((*itr)->GetPartReference()); IViewDescriptor::Pointer desc = page->GetViewFactory()->GetViewRegistry() ->Find(ref->GetId()); if(desc && desc->IsRestorable()) { IMemento::Pointer viewMemento = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref.Cast())); } } // // save all fastview state // if (fastViewManager != 0) // fastViewManager.saveState(memento); // Save the view layout recs. for (QHash::iterator i = mapIDtoViewLayoutRec.begin(); i != mapIDtoViewLayoutRec.end(); ++i) { QString compoundId(i.key()); ViewLayoutRec::Pointer rec(i.value()); if (rec && (!rec->isCloseable || !rec->isMoveable || rec->isStandalone)) { IMemento::Pointer layoutMemento(memento ->CreateChild(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); layoutMemento->PutString(WorkbenchConstants::TAG_ID, compoundId); if (!rec->isCloseable) { layoutMemento->PutString(WorkbenchConstants::TAG_CLOSEABLE, WorkbenchConstants::FALSE_VAL); } if (!rec->isMoveable) { layoutMemento->PutString(WorkbenchConstants::TAG_MOVEABLE, WorkbenchConstants::FALSE_VAL); } if (rec->isStandalone) { layoutMemento->PutString(WorkbenchConstants::TAG_STANDALONE, WorkbenchConstants::TRUE_VAL); layoutMemento->PutString(WorkbenchConstants::TAG_SHOW_TITLE, rec->showTitle ? WorkbenchConstants::TRUE_VAL : WorkbenchConstants::FALSE_VAL); } } } // Save the layout. IMemento::Pointer childMem(memento->CreateChild(WorkbenchConstants::TAG_LAYOUT)); //result.add(presentation.saveState(childMem)); result &= presentation->SaveState(childMem); // Save the editor visibility state if (this->IsEditorAreaVisible()) { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 0); } // // Save the trim state of the editor area if using the new min/max // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // int trimState = editorAreaState; // trimState |= editorAreaRestoreOnUnzoom ? 4 : 0; // memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState); // } // Save the fixed state if (fixed) { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 0); } return result; } void Perspective::SetPerspectiveActionIds(const QList& list) { perspectiveShortcuts = list; } void Perspective::SetShowInPartIds(const QList& list) { showInPartIds = list; } void Perspective::SetShowViewActionIds(const QList& list) { showViewShortcuts = list; } void Perspective::ShowEditorArea() { if (this->IsEditorAreaVisible()) { return; } editorHidden = false; // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) { // If the editor area is going to show then we have to restore // if (getPresentation().getMaximizedStack() != 0) // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); this->ShowEditorAreaLocal(); } // else // setEditorAreaTrimVisibility(true); } else { this->ShowEditorAreaLocal(); } } void Perspective::ShowEditorAreaLocal() { if (editorHolder == 0 || editorHidden) { return; } // Replace the part holder with the editor area. presentation->GetLayout()->Replace(editorHolder, editorArea); editorHolder = 0; } void Perspective::SetEditorAreaState(int newState) { if (newState == editorAreaState) return; editorAreaState = newState; // // reset the restore flag if we're not minimized // if (newState != IStackPresentationSite::STATE_MINIMIZED) // editorAreaRestoreOnUnzoom = false; this->RefreshEditorAreaVisibility(); } int Perspective::GetEditorAreaState() { return editorAreaState; } void Perspective::RefreshEditorAreaVisibility() { // Nothing shows up if the editor area isn't visible at all if (editorHidden) { this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(false); return; } PartStack::Pointer editorStack = editorArea.Cast()->GetUpperRightEditorStack(); if (editorStack == 0) return; // Whatever we're doing, make the current editor stack match it //editorStack->SetStateLocal(editorAreaState); // If it's minimized then it's in the trim if (editorAreaState == IStackPresentationSite::STATE_MINIMIZED) { // Hide the editor area and show its trim this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(true); } else { // Show the editor area and hide its trim //setEditorAreaTrimVisibility(false); this->ShowEditorAreaLocal(); // if (editorAreaState == IStackPresentationSite::STATE_MAXIMIZED) // getPresentation().setMaximizedStack(editorStack); } } IViewReference::Pointer Perspective::GetViewReference(const QString& viewId, const QString& secondaryId) { IViewReference::Pointer ref = page->FindViewReference(viewId, secondaryId); if (ref == 0) { ViewFactory* factory = this->GetViewFactory(); try { ref = factory->CreateView(viewId, secondaryId); } catch (PartInitException& /*e*/) { // IStatus status = StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e); // StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$ // StatusManager.LOG); //TODO Perspective status message WorkbenchPlugin::Log("Failed to create view: id=" + viewId); } } return ref; } IViewPart::Pointer Perspective::ShowView(const QString& viewId, const QString& secondaryId) { ViewFactory* factory = this->GetViewFactory(); IViewReference::Pointer ref = factory->CreateView(viewId, secondaryId); IViewPart::Pointer part = ref->GetPart(true).Cast(); if (part == 0) { throw PartInitException("Could not create view: " + ref->GetId()); } PartSite::Pointer site = part->GetSite().Cast(); PartPane::Pointer pane = site->GetPane(); //TODO Perspective preference store // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE); // // if (openViewMode == IPreferenceConstants.OVM_FAST && // fastViewManager != 0) // { // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true); // setActiveFastView(ref); // } // else if (openViewMode == IPreferenceConstants.OVM_FLOAT // && presentation.canDetach()) // { // presentation.addDetachedPart(pane); // } // else // { if (this->UseNewMinMax(Perspective::Pointer(this))) { // Is this view going to show in the trim? // LayoutPart vPart = presentation.findPart(viewId, secondaryId); // Determine if there is a trim stack that should get the view QString trimId; // // If we can locate the correct trim stack then do so // if (vPart != 0) // { // String id = 0; // ILayoutContainer container = vPart.getContainer(); // if (container.Cast() != 0) // id = ((ContainerPlaceholder)container).getID(); // else if (container.Cast() != 0) // id = ((ViewStack)container).getID(); // // // Is this place-holder in the trim? // if (id != 0 && fastViewManager.getFastViews(id).size()> 0) // { // trimId = id; // } // } // // // No explicit trim found; If we're maximized then we either have to find an // // arbitrary stack... // if (trimId == 0 && presentation.getMaximizedStack() != 0) // { // if (vPart == 0) // { // ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack(); // if (blTrimStack != 0) // { // // OK, we've found a trim stack to add it to... // trimId = blTrimStack.getId(); // // // Since there was no placeholder we have to add one // LayoutPart blPart = presentation.findPart(trimId, 0); // if (blPart.Cast() != 0) // { // ContainerPlaceholder cph = (ContainerPlaceholder) blPart; // if (cph.getRealContainer().Cast() != 0) // { // ViewStack vs = (ViewStack) cph.getRealContainer(); // // // Create a 'compound' id if this is a multi-instance part // String compoundId = ref.getId(); // if (ref.getSecondaryId() != 0) // compoundId = compoundId + ':' + ref.getSecondaryId(); // // // Add the new placeholder // vs.add(new PartPlaceholder(compoundId)); // } // } // } // } // } // // // If we have a trim stack located then add the view to it // if (trimId != "") // { // fastViewManager.addViewReference(trimId, -1, ref, true); // } // else // { // bool inMaximizedStack = vPart != 0 && vPart.getContainer() == presentation.getMaximizedStack(); // Do the default behavior presentation->AddPart(pane); // // Now, if we're maximized then we have to minimize the new stack // if (presentation.getMaximizedStack() != 0 && !inMaximizedStack) // { // vPart = presentation.findPart(viewId, secondaryId); // if (vPart != 0 && vPart.getContainer().Cast() != 0) // { // ViewStack vs = (ViewStack)vPart.getContainer(); // vs.setState(IStackPresentationSite.STATE_MINIMIZED); // // // setting the state to minimized will create the trim toolbar // // so we don't need a 0 pointer check here... // fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true); // } // } // } } else { presentation->AddPart(pane); } //} // Ensure that the newly showing part is enabled if (pane != 0 && pane->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(pane->GetControl(), true); return part; } IWorkbenchPartReference::Pointer Perspective::GetOldPartRef() { return oldPartRef; } void Perspective::SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef) { this->oldPartRef = oldPartRef; } bool Perspective::IsCloseable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isCloseable; } return true; } bool Perspective::IsMoveable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isMoveable; } return true; } void Perspective::DescribeLayout(QString& buf) const { // QList fastViews = getFastViews(); // // if (fastViews.length != 0) // { // buf.append("fastviews ("); //$NON-NLS-1$ // for (int idx = 0; idx < fastViews.length; idx++) // { // IViewReference ref = fastViews[idx]; // // if (idx> 0) // { // buf.append(", "); //$NON-NLS-1$ // } // // buf.append(ref.getPartName()); // } // buf.append("), "); //$NON-NLS-1$ // } this->GetPresentation()->DescribeLayout(buf); } void Perspective::TestInvariants() { this->GetPresentation()->GetLayout()->TestInvariants(); } bool Perspective::UseNewMinMax(Perspective::Pointer activePerspective) { // We need to have an active perspective if (activePerspective == 0) return false; // We need to have a trim manager (if we don't then we // don't create a FastViewManager because it'd be useless) // if (activePerspective->GetFastViewManager() == 0) // return false; // Make sure we don't NPE anyplace WorkbenchWindow::Pointer wbw = activePerspective->page->GetWorkbenchWindow().Cast(); if (wbw == 0) return false; // WorkbenchWindowConfigurer* configurer = wbw->GetWindowConfigurer(); // if (configurer == 0) // return false; IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); if (factory == 0) return false; // Ok, we should be good to go, return the pref //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h index 77eab7d072..422863a217 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h @@ -1,636 +1,636 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVE_H_ #define BERRYPERSPECTIVE_H_ #include #include "berryPerspectiveDescriptor.h" #include "berryPartPlaceholder.h" #include "berryViewLayoutRec.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryPageLayout.h" #include "berryPartPane.h" #include "berryIWorkbenchPartReference.h" #include "berryIViewReference.h" #include "berryIViewPart.h" namespace berry { class ViewFactory; class PerspectiveHelper; /** * \ingroup org_blueberry_ui_internal * */ class Perspective : public Object { public: berryObjectMacro(Perspective) friend class WorkbenchPage; - bool ContainsView(const std::string& viewId); + bool ContainsView(const QString& viewId) const; private: ViewFactory* viewFactory; QHash mapIDtoViewLayoutRec; static const QString VERSION_STRING; // = "0.016"; /** * Reference to the part that was previously active * when this perspective was deactivated. */ IWorkbenchPartReference::Pointer oldPartRef; protected: PerspectiveDescriptor::Pointer descriptor; WorkbenchPage* page; // Editor Area management LayoutPart::Pointer editorArea; PartPlaceholder::Pointer editorHolder; bool editorHidden; int editorAreaState; //ArrayList alwaysOnActionSets; //ArrayList alwaysOffActionSets; QList showViewShortcuts; QList perspectiveShortcuts; bool fixed; QList showInPartIds; //HashMap showInTimes; IMemento::Pointer memento; PerspectiveHelper* presentation; bool shouldHideEditorsOnActivate; PageLayout::Pointer layout; /** * ViewManager constructor comment. */ public: Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page); /** * ViewManager constructor comment. */ protected: Perspective(WorkbenchPage::Pointer page); protected: void Init(WorkbenchPage::Pointer page); /** * Moves a part forward in the Z order of a perspective so it is visible. * * @param part the part to bring to move forward * @return true if the part was brought to top, false if not. */ public: bool BringToTop(IViewReference::Pointer ref); /** * Returns whether a view exists within the perspective. */ public: bool ContainsView(IViewPart::Pointer view); /** * Create the initial list of action sets. */ // protected: void CreateInitialActionSets(List outputList, List stringList) { // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // Iterator iter = stringList.iterator(); // while (iter.hasNext()) { // String id = (String) iter.next(); // IActionSetDescriptor desc = reg.findActionSet(id); // if (desc != null) { // outputList.add(desc); // } else { // WorkbenchPlugin.log("Unable to find Action Set: " + id);//$NON-NLS-1$ // } // } // } /** * Create a presentation for a perspective. */ private: void CreatePresentation(PerspectiveDescriptor::Pointer persp); /** * Dispose the perspective and all views contained within. */ public: ~Perspective(); private: void DisposeViewRefs(); /** * Finds the view with the given ID that is open in this page, or null * if not found. * * @param viewId the view ID */ public: IViewReference::Pointer FindView(const QString& viewId); /** * Finds the view with the given id and secondary id that is open in this page, * or null if not found. * * @param viewId the view ID * @param secondaryId the secondary ID */ public: IViewReference::Pointer FindView(const QString& id, const QString& secondaryId); /** * Returns the window's client composite widget * which views and editor area will be parented. */ public: void* GetClientComposite(); /** * Returns the perspective. */ public: IPerspectiveDescriptor::Pointer GetDesc(); /** * Returns the pane for a view reference. */ protected: PartPane::Pointer GetPane(IViewReference::Pointer ref); /** * Returns the perspective shortcuts associated with this perspective. * * @return an array of perspective identifiers */ public: QList GetPerspectiveShortcuts(); /** * Returns the presentation. */ public: PerspectiveHelper* GetPresentation() const; /** * Returns the show view shortcuts associated with this perspective. * * @return an array of view identifiers */ public: QList GetShowViewShortcuts(); /** * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: QList GetViewReferences(); /** * Hide the editor area if visible */ protected: void HideEditorArea(); /** * Hide the editor area if visible */ protected: void HideEditorAreaLocal(); public: bool HideView(IViewReference::Pointer ref); /* * Return whether the editor area is visible or not. */ protected: bool IsEditorAreaVisible(); /** * Returns the view layout rec for the given view reference, * or null if not found. If create is true, it creates the record * if not already created. */ public: ViewLayoutRec::Pointer GetViewLayoutRec(IViewReference::Pointer ref, bool create); /** * Returns the view layout record for the given view id * or null if not found. If create is true, it creates the record * if not already created. */ private: ViewLayoutRec::Pointer GetViewLayoutRec(const QString& viewId, bool create); /** * Returns true if a layout or perspective is fixed. */ public: bool IsFixedLayout(); /** * Returns true if a view is standalone. * * @since 3.0 */ public: bool IsStandaloneView(IViewReference::Pointer ref); /** * Returns whether the title for a view should * be shown. This applies only to standalone views. * * @since 3.0 */ public: bool GetShowTitleView(IViewReference::Pointer ref); /** * Creates a new presentation from a persistence file. * Note: This method should not modify the current state of the perspective. */ private: void LoadCustomPersp(PerspectiveDescriptor::Pointer persp); private: void UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status); /** * Create a presentation for a perspective. * Note: This method should not modify the current state of the perspective. */ protected: void LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp); // private: void RemoveAlwaysOn(IActionSetDescriptor::Pointer descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOnActionSets.contains(descriptor)) { // return; // } // // alwaysOnActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); // } // } // protected: void AddAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_MASK); // } // removeAlwaysOn(descriptor); // } // protected: void AddAlwaysOn(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOnActionSets.contains(descriptor)) { // return; // } // alwaysOnActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_SHOW); // } // removeAlwaysOff(descriptor); // } // private: void RemoveAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK); // } // } /** * activate. */ protected: void OnActivate(); private: /** * An 'orphan' perspective is one that was originally created through a * contribution but whose contributing bundle is no longer available. In * order to allow it to behave correctly within the environment (for Close, * Reset...) we turn it into a 'custom' perspective on its first activation. */ void FixOrphan(); /** * deactivate. */ protected: void OnDeactivate(); /** * Notifies that a part has been activated. */ public: void PartActivated(IWorkbenchPart::Pointer activePart); /** * The user successfully performed a Show In... action on the specified part. * Update the history. */ public: void PerformedShowIn(const QString& partId); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(IMemento::Pointer memento); bool CreateReferences(const QList& views); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(); /** * Returns the ActionSets read from perspectiveExtensions in the registry. */ // protected: ArrayList GetPerspectiveExtensionActionSets() { // PerspectiveExtensionReader reader = new PerspectiveExtensionReader(); // reader // .setIncludeOnlyTags(new String[] { IWorkbenchRegistryConstants.TAG_ACTION_SET }); // PageLayout layout = new PageLayout(); // reader.extendLayout(null, descriptor.getOriginalId(), layout); // return layout.getActionSets(); // } /** * Returns the Show In... part ids read from the registry. */ protected: QList GetShowInIdsFromRegistry(); /** * Save the layout. */ public: void SaveDesc(); /** * Save the layout. */ public: void SaveDescAs(IPerspectiveDescriptor::Pointer desc); /** * Save the layout. */ public: bool SaveState(IMemento::Pointer memento); /** * Save the layout. */ private: bool SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState); // public: void turnOnActionSets(IActionSetDescriptor[] newArray) { // for (int i = 0; i < newArray.length; i++) { // IActionSetDescriptor descriptor = newArray[i]; // // addAlwaysOn(descriptor); // } // } // public: void turnOffActionSets(IActionSetDescriptor[] toDisable) { // for (int i = 0; i < toDisable.length; i++) { // IActionSetDescriptor descriptor = toDisable[i]; // // turnOffActionSet(descriptor); // } // } // public: void turnOffActionSet(IActionSetDescriptor toDisable) { // addAlwaysOff(toDisable); // } /** * Sets the perspective actions for this page. * This is List of Strings. */ public: void SetPerspectiveActionIds(const QList& list); /** * Sets the ids of the parts to list in the Show In... prompter. * This is a List of Strings. */ public: void SetShowInPartIds(const QList& list); /** * Sets the ids of the views to list in the Show View shortcuts. * This is a List of Strings. */ public: void SetShowViewActionIds(const QList& list); /** * Show the editor area if not visible */ protected: void ShowEditorArea(); /** * Show the editor area if not visible */ protected: void ShowEditorAreaLocal(); public: void SetEditorAreaState(int newState); public: int GetEditorAreaState(); /** * */ public: void RefreshEditorAreaVisibility(); /** * Resolves a view's id into its reference, creating the * view if necessary. * * @param viewId The primary id of the view (must not be * null * @param secondaryId The secondary id of a multiple-instance view * (may be null). * * @return The reference to the specified view. This may be null if the * view fails to create (i.e. thrown a PartInitException) */ public: IViewReference::Pointer GetViewReference(const QString& viewId, const QString& secondaryId); /** * Shows the view with the given id and secondary id. */ public: IViewPart::Pointer ShowView(const QString& viewId, const QString& secondaryId); /** * Returns the old part reference. * Returns null if there was no previously active part. * * @return the old part reference or null */ public: IWorkbenchPartReference::Pointer GetOldPartRef(); /** * Sets the old part reference. * * @param oldPartRef The old part reference to set, or null */ public: void SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef); // //for dynamic UI // protected: void AddActionSet(IActionSetDescriptor newDesc) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(newDesc.getId())) { // removeAlwaysOn(desc); // removeAlwaysOff(desc); // break; // } // } // addAlwaysOn(newDesc); // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // // for dynamic UI // /* package */void removeActionSet(String id) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOn(desc); // break; // } // } // // for (int i = 0; i < alwaysOffActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOffActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOff(desc); // break; // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // void removeActionSet(IActionSetDescriptor toRemove) { // removeAlwaysOn(toRemove); // removeAlwaysOff(toRemove); // } /** * Returns whether the given view is closeable in this perspective. * * @since 3.0 */ public: bool IsCloseable(IViewReference::Pointer reference); /** * Returns whether the given view is moveable in this perspective. * * @since 3.0 */ public: bool IsMoveable(IViewReference::Pointer reference); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. *

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

* * @param buf */ public: void DescribeLayout(QString& buf) const; /** * Sanity-checks the LayoutParts in this perspective. Throws an Assertation exception * if an object's internal state is invalid. */ public: void TestInvariants(); // public: IActionSetDescriptor[] getAlwaysOnActionSets() { // return (IActionSetDescriptor[]) alwaysOnActionSets.toArray(new IActionSetDescriptor[alwaysOnActionSets.size()]); // } // public: IActionSetDescriptor[] getAlwaysOffActionSets() { // return (IActionSetDescriptor[]) alwaysOffActionSets.toArray(new IActionSetDescriptor[alwaysOffActionSets.size()]); // } /** * Used to restrict the use of the new min/max behavior to envoronments * in which it has a chance of working... * * @param activePerspective We pass this in as an arg so others won't have * to check it for 'null' (which is one of the failure cases) * */ public: static bool UseNewMinMax(Perspective::Pointer activePerspective); }; } #endif /*BERRYPERSPECTIVE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp index faecdba123..9659589fd5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp @@ -1,335 +1,331 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPerspectiveDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveRegistry.h" #include "berryStatus.h" #include "berryIContributor.h" namespace berry { PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, const QString& label, PerspectiveDescriptor::Pointer originalDescriptor) : singleton(false), fixed(false) { this->id = id; this->label = label; if (originalDescriptor != 0) { this->originalId = originalDescriptor->GetOriginalId(); this->imageDescriptor = originalDescriptor->imageDescriptor; // This perspective is based on a perspective in some bundle -- if // that // bundle goes away then I think it makes sense to treat this // perspective // the same as any other -- so store it with the original // descriptor's // bundle's list. // // It might also make sense the other way...removing the following // line // will allow the perspective to stay around when the originating // bundle // is unloaded. // // This might also have an impact on upgrade cases -- should we // really be // destroying all user customized perspectives when the older // version is // removed? // // I'm leaving this here for now since its a good example, but // wouldn't be // surprised if we ultimately decide on the opposite. // // The reason this line is important is that this is the value used // to // put the object into the UI level registry. When that bundle goes // away, // the registry will remove the entire list of objects. So if this // desc // has been put into that list -- it will go away. this->pluginId = originalDescriptor->GetPluginId(); } } PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement) : singleton(false), fixed(false) { this->configElement = configElement; this->id = id; // Sanity check. if ((this->GetId() == "") || (this->GetLabel() == "") || (this->GetFactoryClassName() == "")) { IStatus::Pointer status(new Status( IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, QString("Invalid extension (missing label, id or class name): ") + GetId())); throw CoreException(status); } } IPerspectiveFactory::Pointer PerspectiveDescriptor::CreateFactory() { // if there is an originalId, then use that descriptor instead if (originalId != "") { // Get the original descriptor to create the factory. If the // original is gone then nothing can be done. IPerspectiveDescriptor::Pointer target = dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()) ->FindPerspectiveWithId( originalId); return target == 0 ? IPerspectiveFactory::Pointer(0) : target.Cast< PerspectiveDescriptor> ()->CreateFactory(); } // otherwise try to create the executable extension if (configElement != 0) { try { IPerspectiveFactory::Pointer factory( configElement ->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return factory; } catch (const CoreException& /*e*/) { // do nothing } } return IPerspectiveFactory::Pointer(0); } void PerspectiveDescriptor::DeleteCustomDefinition() { dynamic_cast (WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry())->DeleteCustomDefinition( PerspectiveDescriptor::Pointer(this)); } QString PerspectiveDescriptor::GetDescription() const { return configElement == 0 ? description : RegistryReader::GetDescription( configElement); } +void PerspectiveDescriptor::SetDescription(const QString& desc) +{ + description = desc; +} + bool PerspectiveDescriptor::GetFixed() const { if (configElement == 0) return fixed; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_FIXED).compare("true", Qt::CaseInsensitive) == 0; } -std::vector< std::string> PerspectiveDescriptor::GetKeywordReferences() const +QStringList PerspectiveDescriptor::GetKeywordReferences() const { - std::vector result; + QStringList result; if (configElement.IsNull()) { return result; } - std::string keywordRefId; - std::vector keywordRefs; - berry::IConfigurationElement::vector::iterator keywordRefsIt; - keywordRefs = configElement->GetChildren("keywordReference"); - for (keywordRefsIt = keywordRefs.begin() - ; keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs + auto keywordRefs = configElement->GetChildren("keywordReference"); + for (auto keywordRefsIt = keywordRefs.begin(); + keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { - (*keywordRefsIt)->GetAttribute("id", keywordRefId); - result.push_back(keywordRefId); + result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString PerspectiveDescriptor::GetId() const { return id; } QString PerspectiveDescriptor::GetPluginId() const { return configElement == 0 ? pluginId : configElement->GetContributor()->GetName(); } ImageDescriptor::Pointer PerspectiveDescriptor::GetImageDescriptor() const { if (imageDescriptor) return imageDescriptor; if (configElement) { QString icon = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); if (!icon.isEmpty()) { imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configElement->GetContributor()->GetName(), icon); } } if (!imageDescriptor) { imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); } return imageDescriptor; } -std::vector PerspectiveDescriptor::GetCategoryPath() +QStringList PerspectiveDescriptor::GetCategoryPath() const { - std::string category; - categoryPath.clear(); + if(!categoryPath.empty()) return categoryPath; - if (configElement.IsNotNull() && configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY, category)) + if (configElement.IsNotNull()) { - Poco::StringTokenizer stok(category, "/", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); - // Parse the path tokens and store them - for (Poco::StringTokenizer::Iterator iter = stok.begin(); iter != stok.end(); ++iter) - { - categoryPath.push_back(*iter); - } + QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); + categoryPath = category.split('/', QString::SkipEmptyParts); } return categoryPath; } QString PerspectiveDescriptor::GetLabel() const { if (configElement == 0) return label; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString PerspectiveDescriptor::GetOriginalId() const { if (originalId == "") { return this->GetId(); } return originalId; } bool PerspectiveDescriptor::HasCustomDefinition() const { return dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry())->HasCustomDefinition( PerspectiveDescriptor::ConstPointer(this)); } bool PerspectiveDescriptor::HasDefaultFlag() const { if (configElement == 0) { return false; } return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::IsPredefined() const { return this->GetFactoryClassName() != "" && configElement != 0; } bool PerspectiveDescriptor::IsSingleton() const { if (configElement == 0) return singleton; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_SINGLETON).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::RestoreState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->GetChild( WorkbenchConstants::TAG_DESCRIPTOR)); if (childMem) { childMem->GetString(WorkbenchConstants::TAG_ID, id); childMem->GetString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); childMem->GetString(WorkbenchConstants::TAG_LABEL, label); childMem->GetString(WorkbenchConstants::TAG_CLASS, className); int singletonVal; singleton = childMem->GetInteger(WorkbenchConstants::TAG_SINGLETON, singletonVal); // Find a descriptor in the registry. IPerspectiveDescriptor::Pointer descriptor = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry()->FindPerspectiveWithId( this->GetOriginalId()); if (descriptor) { // Copy the state from the registred descriptor. imageDescriptor = descriptor->GetImageDescriptor(); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ return true; } void PerspectiveDescriptor::RevertToPredefined() { if (this->IsPredefined()) { this->DeleteCustomDefinition(); } } bool PerspectiveDescriptor::SaveState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->CreateChild( WorkbenchConstants::TAG_DESCRIPTOR)); childMem->PutString(WorkbenchConstants::TAG_ID, GetId()); if (!originalId.isEmpty()) { childMem->PutString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); } childMem->PutString(WorkbenchConstants::TAG_LABEL, GetLabel()); childMem->PutString(WorkbenchConstants::TAG_CLASS, GetFactoryClassName()); if (singleton) { childMem->PutInteger(WorkbenchConstants::TAG_SINGLETON, 1); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); return true; } IConfigurationElement::Pointer PerspectiveDescriptor::GetConfigElement() const { return configElement; } QString PerspectiveDescriptor::GetFactoryClassName() const { return configElement == 0 ? className : RegistryReader::GetClassValue( configElement, WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h index 0b0cd0ada6..33e52434b2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h @@ -1,244 +1,245 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVEDESCRIPTOR_H_ #define BERRYPERSPECTIVEDESCRIPTOR_H_ #include #include "berryIPerspectiveDescriptor.h" #include "berryIPerspectiveFactory.h" #include "berryIMemento.h" +#include namespace berry { /** * \ingroup org_blueberry_ui_internal * * PerspectiveDescriptor. *

* A PerspectiveDesciptor has 3 states: *

*
    *
  1. It isPredefined(), in which case it was defined from an * extension point.
  2. *
  3. It isPredefined() and hasCustomFile, in * which case the user has customized a predefined perspective.
  4. *
  5. It hasCustomFile, in which case the user created a new * perspective.
  6. *
* */ class PerspectiveDescriptor : public IPerspectiveDescriptor { public: berryObjectMacro(PerspectiveDescriptor); private: QString id; QString pluginId; QString originalId; QString label; QString className; QString description; bool singleton; bool fixed; mutable ImageDescriptor::Pointer imageDescriptor; IConfigurationElement::Pointer configElement; - std::vector categoryPath; + mutable QStringList categoryPath; /** * Create a new empty descriptor. * * @param id * the id of the new descriptor * @param label * the label of the new descriptor * @param originalDescriptor * the descriptor that this descriptor is based on */ public: PerspectiveDescriptor(const QString& id, const QString& label, PerspectiveDescriptor::Pointer originalDescriptor); /** * Create a descriptor from a config element. * * @param id * the id of the element to create * @param configElement * the element to base this perspective on * @throws CoreException * thrown if there are any missing attributes */ public: PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement); /** * Creates a factory for a predefined perspective. If the perspective is not * predefined return null. * * @return the IPerspectiveFactory or null * @throws CoreException * if the object could not be instantiated. */ public: IPerspectiveFactory::Pointer CreateFactory(); /** * Deletes the custom definition for a perspective.. */ public: void DeleteCustomDefinition(); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getDescription() */ public: QString GetDescription() const; - public: void SetDescription(std::string desc) {description = desc; } + public: void SetDescription(const QString& desc); - std::vector GetKeywordReferences() const; + QStringList GetKeywordReferences() const; /** * Returns whether or not this perspective is fixed. * * @return whether or not this perspective is fixed */ public: bool GetFixed() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getId() */ public: QString GetId() const; public: QString GetPluginId() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getImageDescriptor() */ public: ImageDescriptor::Pointer GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getLabel() */ public: QString GetLabel() const; /** * Return the original id of this descriptor. * * @return the original id of this descriptor */ public: QString GetOriginalId() const; /** * Returns true if this perspective has a custom definition. * * @return whether this perspective has a custom definition */ public: bool HasCustomDefinition() const; /** * Returns true if this perspective wants to be default. * * @return whether this perspective wants to be default */ public: bool HasDefaultFlag() const; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ public: bool IsPredefined() const; /** * Returns true if this perspective is a singleton. * * @return whether this perspective is a singleton */ public: bool IsSingleton() const; /** * Restore the state of a perspective from a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ public: bool RestoreState(IMemento::Pointer memento); /** * Revert to the predefined extension template. Does nothing if this * descriptor is user defined. */ public: void RevertToPredefined(); /** * Save the state of a perspective to a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ public: bool SaveState(IMemento::Pointer memento); /** * Return the configuration element used to create this perspective, if one * was used. * * @return the configuration element used to create this perspective * @since 3.0 */ public: IConfigurationElement::Pointer GetConfigElement() const; /** * Returns the factory class name for this descriptor. * * @return the factory class name for this descriptor * @since 3.1 */ public: QString GetFactoryClassName() const; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ - public: std::vector GetCategoryPath(); + public: QStringList GetCategoryPath() const; }; } #endif /*BERRYPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp index 6047ab95a3..d3f696e88a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp @@ -1,1492 +1,1492 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryEditorSashContainer.h" #include "berryDragUtil.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchConstants.h" #include namespace berry { const int PerspectiveHelper::MIN_DETACH_WIDTH = 150; const int PerspectiveHelper::MIN_DETACH_HEIGHT = 250; PerspectiveHelper::DragOverListener::DragOverListener(PerspectiveHelper* perspHelper) : perspHelper(perspHelper) { } IDropTarget::Pointer PerspectiveHelper::DragOverListener::Drag( void* /*currentControl*/, const Object::Pointer& draggedObject, const Point& /*position*/, const Rectangle& dragRectangle) { if (draggedObject.Cast() != 0) { PartPane::Pointer part = draggedObject.Cast(); if (part->GetContainer().Cast()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); // Views that haven't been shown yet have no 'control' which causes // 'GetWorkbenchWindow' to return 'null' so check explicitly if (part->GetPage() != perspHelper->page) return IDropTarget::Pointer(0); else if (part->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, part, dragRectangle); else perspHelper->dropTarget->SetTarget(part, dragRectangle); } else if (draggedObject.Cast() != 0) { PartStack::Pointer stack = draggedObject.Cast(); if (stack->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); if (stack->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, stack, dragRectangle); else perspHelper->dropTarget->SetTarget(stack, dragRectangle); } return perspHelper->dropTarget; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartPane::Pointer part, const Rectangle& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, const Rectangle& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const Rectangle& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, const Rectangle& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(stack, dragRectangle); } void PerspectiveHelper::ActualDropTarget::Drop() { if (part != 0) { Shell::Pointer shell = part->GetShell(); if (shell->GetData().Cast () != 0) { // if only one view in tab folder then do a window move ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { if (container.Cast()->GetItemCount() == 1) { shell->SetLocation(dragRectangle.x, dragRectangle.y); return; } } } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->DetachPart(part, dragRectangle.x, dragRectangle.y); } else if (stack != 0) { Shell::Pointer shell = stack->GetShell(); if (shell->GetData().Cast () != 0) { // only one tab folder in a detach window, so do window // move shell->SetLocation(dragRectangle.x, dragRectangle.y); return; } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->Detach(stack, dragRectangle.x, dragRectangle.y); } } DnDTweaklet::CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { return DnDTweaklet::CURSOR_OFFSCREEN; } PerspectiveHelper::MatchingPart::MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part) { this->pid = pid; this->sid = sid; this->part = part; this->len = pid.size() + sid.size(); this->hasWildcard = (pid.indexOf(PartPlaceholder::WILD_CARD) != -1) || (sid.indexOf(PartPlaceholder::WILD_CARD) != -1); } bool PerspectiveHelper::CompareMatchingParts::operator()(const MatchingPart& m1, const MatchingPart& m2) const { // specific ids always outweigh ids with wildcards if (m1.hasWildcard && !m2.hasWildcard) { return true; } if (!m1.hasWildcard && m2.hasWildcard) { return false; } // if both are specific or both have wildcards, simply compare based on length return m1.len > m2.len; } PerspectiveHelper::PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* persp) : page(workbenchPage), perspective(persp), mainLayout(mainLayout), detachable(false), active(false) { // Views can be detached if the feature is enabled (true by default, // use the plug-in customization file to disable), and if the platform // supports detaching. this->dragTarget.reset(new DragOverListener(this)); //TODO preference store // IPreferenceStore store = PlatformUI.getPreferenceStore(); // this.detachable = store.getBoolean( // IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS); this->detachable = true; if (this->detachable) { // Check if some arbitrary Composite supports reparenting. If it // doesn't, views cannot be detached. void* client = workbenchPage->GetClientComposite(); if (client == 0) { // The workbench page is not initialized. I don't think this can happen, // but if it does, silently set detachable to false. this->detachable = false; } else { this->detachable = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsReparentable(client); } } } void PerspectiveHelper::Activate(void* parent) { if (active) { return; } parentWidget = parent; // Activate main layout // make sure all the views have been properly parented QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { PartPane::Pointer part = *iter; part->Reparent(parent); } mainLayout->CreateControl(parent); mainLayout->SetActive(true); // Open the detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Open(); } this->EnableAllDrag(); // // Ensure that the maximized stack's presentation state is correct // if (maximizedStackId != 0) // { // LayoutPart part = this->FindPart(maximizedStackId); // if (part.Cast() != 0) // { // maximizedStack = (PartStack) part; // maximizedStackId = 0; // } // } // // // NOTE: we only handle ViewStacks here; Editor Stacks are handled by the // // perspective // if (maximizedStack instanceof ViewStack) // { // maximizedStack.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } active = true; } void PerspectiveHelper::AddPart(LayoutPart::Pointer part) { // Look for a placeholder. PartPlaceholder::Pointer placeholder; LayoutPart::Pointer testPart; QString primaryId = part->GetID(); QString secondaryId; IViewReference::Pointer ref; if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast (); ref = pane->GetPartReference().Cast (); if (ref != 0) secondaryId = ref->GetSecondaryId(); } if (secondaryId != "") { testPart = this->FindPart(primaryId, secondaryId); } else { testPart = this->FindPart(primaryId); } // validate the testPart if (testPart != 0 && testPart.Cast() != 0) { placeholder = testPart.Cast (); } // If there is no placeholder do a simple add. Otherwise, replace the // placeholder if its not a pattern matching placholder if (placeholder == 0) { part->Reparent(mainLayout->GetParent()); LayoutPart::Pointer relative = mainLayout->FindBottomRight(); if (relative != 0 && relative.Cast() != 0) { ILayoutContainer::Pointer stack = relative.Cast (); if (stack->AllowsAdd(part)) { mainLayout->Stack(part, stack); } else { mainLayout->AddPart(part); } } else { mainLayout->AddPart(part); } } else { ILayoutContainer::Pointer container = placeholder->GetContainer(); if (container != 0) { if (container.Cast () != 0) { //Create a detached window add the part on it. DetachedPlaceHolder::Pointer holder = container.Cast(); detachedPlaceHolderList.removeAll(holder); container->Remove(testPart); DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); part->CreateControl(window->GetShell()->GetControl()); // Open window. window->GetShell()->SetBounds(holder->GetBounds()); window->Open(); // add part to detached window. PartPane::Pointer pane = part.Cast(); window->Add(pane); QList otherChildren = holder->GetChildren(); for (QList::iterator iter = otherChildren.begin(); iter != otherChildren.end(); ++iter) { part->GetContainer()->Add(*iter); } } else { // show parent if necessary if (container.Cast () != 0) { ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); if (parentContainer == 0) return; container = containerPlaceholder->GetRealContainer().Cast(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } // // reparent part. // if (container.Cast() == 0) // { // // We don't need to reparent children of PartTabFolders since they will automatically // // reparent their children when they become visible. This if statement used to be // // part of an else branch. Investigate if it is still necessary. // part->Reparent(mainLayout->GetParent()); // } // see if we should replace the placeholder if (placeholder->HasWildCard()) { if (PartSashContainer::Pointer sashContainer = container.Cast()) { sashContainer->AddChildForPlaceholder(part, placeholder); } else { container->Add(part); } } else { container->Replace(placeholder, part); } } } } } void PerspectiveHelper::AttachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); // Restore any maximized part before re-attaching. // Note that 'getMaximizedStack != 0' implies 'useNewMinMax' // if (getMaximizedStack() != 0) // { // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } this->DerefPart(pane); this->AddPart(pane); this->BringPartToTop(pane); pane->SetFocus(); } bool PerspectiveHelper::CanDetach() { return detachable; } bool PerspectiveHelper::BringPartToTop(LayoutPart::Pointer part) { ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); if (folder->GetSelection() != part) { folder->SetSelection(part); return true; } } return false; } bool PerspectiveHelper::IsPartVisible(IWorkbenchPartReference::Pointer partRef) { LayoutPart::Pointer foundPart; if (partRef.Cast () != 0) { foundPart = this->FindPart(partRef->GetId(), partRef.Cast()->GetSecondaryId()); } else { foundPart = this->FindPart(partRef->GetId()); } if (foundPart == 0) { return false; } if (foundPart.Cast () != 0) { return false; } ILayoutContainer::Pointer container = foundPart->GetContainer(); if (container.Cast () != 0) { return false; } if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); LayoutPart::Pointer visiblePart = folder->GetSelection(); if (visiblePart == 0) { return false; } return partRef == visiblePart.Cast()->GetPartReference(); } return true; } bool PerspectiveHelper::WillPartBeVisible(const QString& partId) { return this->WillPartBeVisible(partId, 0); } bool PerspectiveHelper::WillPartBeVisible(const QString& partId, const QString& secondaryId) { LayoutPart::Pointer part = this->FindPart(partId, secondaryId); if (part == 0) { return false; } ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { container = container.Cast()->GetRealContainer().Cast(); } if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); if (folder->GetSelection() == 0) { return false; } return part->GetID() == folder->GetSelection()->GetID(); } return true; } QList PerspectiveHelper::CollectPlaceholders() { // Scan the main window. QList results = this->CollectPlaceholders( mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; QList moreResults = win->GetChildren(); if (moreResults.size()> 0) { for (QList::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) results.push_back(iter->Cast()); } } } } return results; } QList PerspectiveHelper::CollectPlaceholders( const QList& parts) { QList result; for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (ILayoutContainer::Pointer container = part.Cast()) { // iterate through sub containers to find sub-parts QList newParts = this->CollectPlaceholders( container->GetChildren()); result.append(newParts); } else if (PartPlaceholder::Pointer placeholder = part.Cast()) { result.push_back(placeholder); } } return result; } void PerspectiveHelper::CollectViewPanes(QList& result) { // Scan the main window. this->CollectViewPanes(result, mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; CollectViewPanes(result, win->GetChildren()); } } } void PerspectiveHelper::CollectViewPanes(QList& result, const QList& parts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (PartPane::Pointer partPane = part.Cast()) { if(partPane->GetPartReference().Cast()) { result.push_back(partPane); } } else if (ILayoutContainer::Pointer container = part.Cast ()) { this->CollectViewPanes(result, container->GetChildren()); } } } void PerspectiveHelper::Deactivate() { if (!active) { return; } this->DisableAllDrag(); // Reparent all views to the main window void* parent = mainLayout->GetParent(); QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer window = *winIter; CollectViewPanes(children, window->GetChildren()); } // *** Do we even need to do this if detached windows not supported? for (QList::iterator itr = children.begin(); itr != children.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } // Dispose main layout. mainLayout->SetActive(false); // Dispose the detached windows for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Close(); } active = false; } PerspectiveHelper::~PerspectiveHelper() { mainLayout->Dispose(); mainLayout->DisposeSashes(); } void PerspectiveHelper::DescribeLayout(QString& buf) const { if (detachable) { if (detachedWindowList.size() != 0) { buf.append("detachedWindows ("); //$NON-NLS-1$ for (DetachedWindowsType::const_iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::ConstPointer window = *winIter; QList children = window->GetChildren(); - unsigned int j = 0; + int j = 0; if (children.size() != 0) { buf.append("dWindow ("); //$NON-NLS-1$ for (QList::iterator partIter = children.begin(); partIter != children.end(); ++partIter, ++j) { if (partIter->Cast() != 0) buf.append(partIter->Cast()->GetPlaceHolderId()); else if (partIter->Cast() != 0) buf.append( partIter->Cast()->GetPartReference()->GetPartName()); if (j < (children.size() - 1)) { buf.append(", "); //$NON-NLS-1$ } } buf.append(")"); //$NON-NLS-1$ } } buf.append("), "); //$NON-NLS-1$ } } this->GetLayout()->DescribeLayout(buf); } void PerspectiveHelper::DerefPart(LayoutPart::Pointer part) { // if (part.Cast () != 0) // { // IViewReference::Pointer ref = ((ViewPane) part).getViewReference(); // if (perspective.isFastView(ref)) // { // // Special check: if it's a fast view then it's actual ViewStack // // may only contain placeholders and the stack is represented in // // the presentation by a container placeholder...make sure the // // PartPlaceHolder for 'ref' is removed from the ViewStack // String id = perspective.getFastViewManager().getIdForRef(ref); // LayoutPart parentPart = findPart(id, 0); // if (parentPart.Cast () != 0) // { // ViewStack vs = // (ViewStack) ((ContainerPlaceholder) parentPart).getRealContainer(); // QList kids = vs.getChildren(); // for (int i = 0; i < kids.length; i++) // { // if (kids[i].Cast () != 0) // { // if (ref.getId().equals(kids[i].id)) // vs.remove(kids[i]); // } // } // } // perspective.getFastViewManager().removeViewReference(ref, true, true); // } // } // Get vital part stats before reparenting. ILayoutContainer::Pointer oldContainer = part->GetContainer(); bool wasDocked = part->IsDocked(); Shell::Pointer oldShell = part->GetShell(); // Reparent the part back to the main window part->Reparent(mainLayout->GetParent()); // Update container. if (oldContainer == 0) { return; } oldContainer->Remove(part); ILayoutContainer::ChildrenType children = oldContainer->GetChildren(); if (wasDocked) { bool hasChildren = (children.size()> 0); if (hasChildren) { // make sure one is at least visible int childVisible = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if ((*iter)->GetControl() != 0) { childVisible++; } } // none visible, then reprarent and remove container if (oldContainer.Cast () != 0) { PartStack::Pointer folder = oldContainer.Cast(); // Is the part in the trim? bool inTrim = false; // // Safety check...there may be no FastViewManager // if (perspective.getFastViewManager() != 0) // inTrim // = perspective.getFastViewManager().getFastViews(folder.getID()).size() // > 0; if (childVisible == 0 && !inTrim) { ILayoutContainer::Pointer parentContainer = folder->GetContainer(); hasChildren = folder->GetChildren().size()> 0; // We maintain the stack as a place-holder if it has children // (which at this point would represent view place-holders) if (hasChildren) { folder->Dispose(); // replace the real container with a ContainerPlaceholder ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(folder->GetID())); placeholder->SetRealContainer(folder); parentContainer->Replace(folder, placeholder); } } else if (childVisible == 1) { LayoutTree::Pointer layout = mainLayout->GetLayoutTree(); layout = layout->Find(folder); layout->SetBounds(layout->GetBounds()); } } } if (!hasChildren) { // There are no more children in this container, so get rid of // it if (oldContainer.Cast () != 0) { //BERRY_INFO << "No children left, removing container\n"; LayoutPart::Pointer parent = oldContainer.Cast(); ILayoutContainer::Pointer parentContainer = parent->GetContainer(); if (parentContainer != 0) { parentContainer->Remove(parent); parent->Print(qDebug()); parent->Dispose(); } } } } else if (!wasDocked) { if (children.empty()) { // There are no more children in this container, so get rid of // it // Turn on redraw again just in case it was off. //oldShell.setRedraw(true); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } else { // There are children. If none are visible hide detached // window. bool allInvisible = true; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible) { DetachedPlaceHolder::Pointer placeholder(new DetachedPlaceHolder("", oldShell->GetBounds())); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { oldContainer->Remove(*iter); (*iter)->SetContainer(placeholder); placeholder->Add(*iter); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); if (part.Cast () != 0) { //window.getShell().setRedraw(false); //parentWidget.setRedraw(false); PartStack::Pointer stack = part.Cast(); LayoutPart::Pointer visiblePart = stack->GetSelection(); ILayoutContainer::ChildrenType children = stack->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (PartPane::Pointer partPane = iter->Cast() // && check it is a view? ) { // remove the part from its current container this->DerefPart(*iter); // add part to detached window. window->Add(*iter); } } if (visiblePart != 0) { this->BringPartToTop(visiblePart); visiblePart->SetFocus(); } //window.getShell().setRedraw(true); //parentWidget.setRedraw(true); } } void PerspectiveHelper::DetachPart(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); // remove the part from its current container this->DerefPart(part); // add part to detached window. window->Add(part); part->SetFocus(); } void PerspectiveHelper::DetachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); if (this->CanDetach() && pane != 0) { // if (getMaximizedStack() != 0) // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); Rectangle bounds = pane->GetParentBounds(); this->DetachPart(pane, bounds.x, bounds.y); } } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part) { // Calculate detached window size. Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); bounds.x = bounds.x + (bounds.width - 300) / 2; bounds.y = bounds.y + (bounds.height - 300) / 2; this->AddDetachedPart(part, bounds); } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part, const Rectangle& bounds) { // Detaching is disabled on some platforms .. if (!detachable) { this->AddPart(part); return; } // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); // add part to detached window. part->CreateControl(window->GetShell()->GetControl()); window->Add(part); // Open window. window->GetShell()->SetBounds(bounds.x, bounds.y, bounds.width, bounds.height); window->Open(); part->SetFocus(); } void PerspectiveHelper::DisableAllDrag() { DragUtil::RemoveDragTarget(0, dragTarget.data()); } void PerspectiveHelper::EnableAllDrag() { DragUtil::AddDragTarget(0, dragTarget.data()); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id) { return this->FindPart(id, ""); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId) { //BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl; // check main window. QList matchingParts; LayoutPart::Pointer part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, mainLayout->GetChildren(), matchingParts) : this->FindPart(primaryId, mainLayout->GetChildren(), matchingParts); if (part != 0) { return part; } // check each detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { DetachedWindow::Pointer window = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, window->GetChildren(), matchingParts) : this->FindPart(primaryId, window->GetChildren(), matchingParts); if (part != 0) { return part; } } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { DetachedPlaceHolder::Pointer holder = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, holder->GetChildren(), matchingParts) : this->FindPart(primaryId, holder->GetChildren(), matchingParts); if (part != 0) { return part; } } //BERRY_INFO << "Looking through the matched parts (count: " << matchingParts.size() << ")\n"; // sort the matching parts if (matchingParts.size()> 0) { std::partial_sort(matchingParts.begin(), (matchingParts.begin()), matchingParts.end(), CompareMatchingParts()); const MatchingPart& mostSignificantPart = matchingParts.front(); return mostSignificantPart.part; } // Not found. return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check for part equality, parts with secondary ids fail if (part->GetID() == id) { if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetSecondaryId() != "") { continue; } } return part; } // check pattern matching placeholders else if (part->IsPlaceHolder() && part.Cast()->HasWildCard()) { QRegExp re(id, Qt::CaseInsensitive); if (re.exactMatch(part->GetID())) { matchingParts.push_back(MatchingPart(part->GetID(), "", part)); } // StringMatcher sm = new StringMatcher(part.getID(), true, false); // if (sm.match(id)) // { // matchingParts .add(new MatchingPart(part.getID(), 0, part)); // } } else if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { part = FindPart(id, layoutContainer->GetChildren(), matchingParts); if (part) { return part; } } } //BERRY_INFO << "Returning 0\n"; return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check containers first if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { LayoutPart::Pointer testPart = FindPart(primaryId, secondaryId, layoutContainer->GetChildren(), matchingParts); if (testPart) { return testPart; } } // check for view part equality if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetId() == primaryId && ref->GetSecondaryId() == secondaryId) { return part; } } // check placeholders else if (part.Cast () != 0) { QString id = part->GetID(); // optimization: don't bother parsing id if it has no separator -- it can't match QString phSecondaryId = ViewFactory::ExtractSecondaryId(id); if (phSecondaryId == "") { // but still need to check for wildcard case if (id == PartPlaceholder::WILD_CARD) { matchingParts.push_back(MatchingPart(id, "", part)); } continue; } QString phPrimaryId = ViewFactory::ExtractPrimaryId(id); // perfect matching pair if (phPrimaryId == primaryId && phSecondaryId == secondaryId) { return part; } // check for partial matching pair QRegExp pre(phPrimaryId, Qt::CaseInsensitive); if (pre.exactMatch(primaryId)) { QRegExp sre(phSecondaryId, Qt::CaseInsensitive); if (sre.exactMatch(secondaryId)) { matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part)); } } } } return LayoutPart::Pointer(0); } bool PerspectiveHelper::HasPlaceholder(const QString& id) { return this->HasPlaceholder(id, 0); } bool PerspectiveHelper::HasPlaceholder(const QString& primaryId, const QString& secondaryId) { LayoutPart::Pointer testPart; if (secondaryId == "") { testPart = this->FindPart(primaryId); } else { testPart = this->FindPart(primaryId, secondaryId); } return (testPart != 0 && testPart.Cast () != 0); } PartSashContainer::Pointer PerspectiveHelper::GetLayout() const { return mainLayout; } bool PerspectiveHelper::IsActive() { return active; } float PerspectiveHelper::GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target) { if ((source.Cast () != 0 || source.Cast () != 0) && target.Cast () != 0) { return 0.25f; } return 0.5f; } void PerspectiveHelper::RemovePart(LayoutPart::Pointer part) { // Reparent the part back to the main window void* parent = mainLayout->GetParent(); part->Reparent(parent); // Replace part with a placeholder ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0) { QString placeHolderId = part->GetPlaceHolderId(); container->Replace(part, LayoutPart::Pointer(new PartPlaceholder(placeHolderId))); // // If the parent is root we're done. Do not try to replace // // it with placeholder. // if (container == mainLayout) // { // return; // } // If the parent is empty replace it with a placeholder. QList children = container->GetChildren(); bool allInvisible = true; for (QList::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible && (container.Cast () != 0)) { // what type of window are we in? LayoutPart::Pointer cPart = container.Cast(); //Window oldWindow = cPart.getWindow(); bool wasDocked = cPart->IsDocked(); Shell::Pointer oldShell = cPart->GetShell(); if (wasDocked) { // PR 1GDFVBY: ViewStack not disposed when page // closed. if (container.Cast () != 0) { container.Cast()->Dispose(); } // replace the real container with a // ContainerPlaceholder ILayoutContainer::Pointer parentContainer = cPart->GetContainer(); ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(cPart->GetID())); placeholder->SetRealContainer(container); parentContainer->Replace(cPart, placeholder); } else { DetachedPlaceHolder::Pointer placeholder( new DetachedPlaceHolder("", oldShell->GetBounds())); //$NON-NLS-1$ for (QList::iterator childIter2 = children.begin(); childIter2 != children.end(); ++childIter2) { (*childIter2)->GetContainer()->Remove(*childIter2); (*childIter2)->SetContainer(placeholder); placeholder->Add(*childIter2); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part) { // Look for a PartPlaceholder that will tell us how to position this // object QList placeholders = this->CollectPlaceholders(); for (int i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetID() == part->GetID()) { // found a matching placeholder which we can replace with the // new View ILayoutContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { if (ContainerPlaceholder::Pointer containerPlaceholder = container.Cast ()) { // One of the children is now visible so replace the // ContainerPlaceholder with the real container ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer().Cast(); if (LayoutPart::Pointer layoutPart = container.Cast ()) { parentContainer->Replace(containerPlaceholder, layoutPart); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } container->Replace(placeholders[i], part); return; } } } } bool PerspectiveHelper::RestoreState(IMemento::Pointer memento) { // Restore main window. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->RestoreState(childMem); bool r = mainLayout->RestoreState(childMem); // Restore each floating window. if (detachable) { QList detachedWindows(memento->GetChildren( WorkbenchConstants::TAG_DETACHED_WINDOW)); for (QList::iterator iter = detachedWindows.begin(); iter != detachedWindows.end(); ++iter) { DetachedWindow::Pointer win(new DetachedWindow(page)); detachedWindowList.push_back(win); win->RestoreState(*iter); } QList childrenMem(memento->GetChildren( WorkbenchConstants::TAG_HIDDEN_WINDOW)); for (QList::iterator iter = childrenMem.begin(); iter != childrenMem.end(); ++iter) { DetachedPlaceHolder::Pointer holder( new DetachedPlaceHolder("", Rectangle(0, 0, 0, 0))); holder->RestoreState(*iter); detachedPlaceHolderList.push_back(holder); } } // Get the cached id of the currently maximized stack //maximizedStackId = childMem.getString(IWorkbenchConstants.TAG_MAXIMIZED); return r; } bool PerspectiveHelper::SaveState(IMemento::Pointer memento) { // Persist main window. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->SaveState(childMem); bool r = mainLayout->SaveState(childMem); if (detachable) { // Persist each detached window. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_DETACHED_WINDOW); (*iter)->SaveState(childMem); } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_HIDDEN_WINDOW); (*iter)->SaveState(childMem); } } // Write out the id of the maximized (View) stack (if any) // NOTE: we only write this out if it's a ViewStack since the // Editor Area is handled by the perspective // if (maximizedStack.Cast () != 0) // { // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, // maximizedStack.getID()); // } // else if (maximizedStackId != 0) // { // // Maintain the cache if the perspective has never been activated // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, maximizedStackId); // } return r; } void PerspectiveHelper::UpdateBoundsMap() { boundsMap.clear(); // Walk the layout gathering the current bounds of each stack // and the editor area QList kids = mainLayout->GetChildren(); for (QList::iterator iter = kids.begin(); iter != kids.end(); ++iter) { if (iter->Cast () != 0) { PartStack::Pointer vs = iter->Cast(); boundsMap.insert(vs->GetID(), vs->GetBounds()); } else if (iter->Cast () != 0) { EditorSashContainer::Pointer esc = iter->Cast(); boundsMap.insert(esc->GetID(), esc->GetBounds()); } } } void PerspectiveHelper::ResetBoundsMap() { boundsMap.clear(); } Rectangle PerspectiveHelper::GetCachedBoundsFor(const QString& id) { return boundsMap[id]; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp index 970c8acd90..a8b181b43c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp @@ -1,591 +1,590 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPerspectiveRegistry.h" #include "berryWorkbench.h" #include "berryWorkbenchPlugin.h" #include "berryPerspectiveRegistryReader.h" - namespace berry { const QString PerspectiveRegistry::EXT = "_persp.xml"; const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP"; const QString PerspectiveRegistry::PERSP = "_persp"; const char PerspectiveRegistry::SPACE_DELIMITER = ' '; PerspectiveRegistry::PerspectiveRegistry() { //IExtensionTracker tracker = PlatformUI.getWorkbench() .getExtensionTracker(); //tracker.registerHandler(this, null); //this->InitializePreferenceChangeListener(); //WorkbenchPlugin::GetDefault()->GetPreferenceStore()->AddPropertyChangeListener( // preferenceListener); } void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc) { if (desc == 0) { return; } this->Add(desc); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Sanity check to avoid invalid or duplicate labels. if (!this->ValidateLabel(label)) { return IPerspectiveDescriptor::Pointer(0); } if (this->FindPerspectiveWithLabel(label) != 0) { return IPerspectiveDescriptor::Pointer(0); } // Calculate ID. QString id(label); id = id.replace(' ', '_').trimmed(); // Create descriptor. PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, label, originalDescriptor.Cast())); this->Add(desc); - return desc.GetPointer(); + return IPerspectiveDescriptor::Pointer(static_cast(desc.GetPointer())); } void PerspectiveRegistry::RevertPerspectives( const QList& perspToRevert) { // indicate that the user is removing these perspectives for (QList::const_iterator iter = perspToRevert.begin(); iter != perspToRevert.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } } void PerspectiveRegistry::DeletePerspectives( const QList& perspToDelete) { for (QList::const_iterator iter = perspToDelete.begin(); iter != perspToDelete.end(); ++iter) { this->DeletePerspective(*iter); } } void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in) { PerspectiveDescriptor::Pointer desc = in.Cast(); // Don't delete predefined perspectives if (!desc->IsPredefined()) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetId() == id) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return null; // } return desc; } } return IPerspectiveDescriptor::Pointer(0); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel( const QString& label) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetLabel() == label) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return 0; // } return desc; } } return IPerspectiveDescriptor::Pointer(0); } QString PerspectiveRegistry::GetDefaultPerspective() { return defaultPerspID; } QList PerspectiveRegistry::GetPerspectives() { // Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives, // new ArrayList()); // return (IPerspectiveDescriptor[]) descs.toArray( // new IPerspectiveDescriptor[descs.size()]); QList result; for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { result.push_back(iter->Cast()); } return result; } void PerspectiveRegistry::Load() { // Load the registries. this->LoadPredefined(); this->LoadCustom(); // Get default perspective. // Get it from the R1.0 dialog settings first. Fixes bug 17039 // IDialogSettings dialogSettings = // WorkbenchPlugin.getDefault() .getDialogSettings(); // QString str = dialogSettings.get(ID_DEF_PERSP); // if (str != null && str.length() > 0) // { // this->SetDefaultPerspective(str); // dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$ // } this->VerifyDefaultPerspective(); } //void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, // XMLMemento::Pointer memento) //{ // // IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); // // // Save it to the preference store. // Writer writer = new StringWriter(); // // memento.save(writer); // writer.close(); // store.setValue(desc.getId() + PERSP, writer.toString()); // //} IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& /*id*/) { //TODO CustomPersp // Reader reader = null; // // IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); // QString xmlString = store.getString(id + PERSP); // if (xmlString != null && xmlString.length() != 0) // { // defined in store // reader = new StringReader(xmlString); // } // XMLMemento memento = XMLMemento.createReadRoot(reader); // reader.close(); // return memento; return IMemento::Pointer(0); } void PerspectiveRegistry::SetDefaultPerspective(const QString& id) { IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { defaultPerspID = id; //TODO Preferences // PrefUtil.getAPIPreferenceStore().setValue( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id); } } bool PerspectiveRegistry::ValidateLabel(const QString& label) { return !label.trimmed().isEmpty(); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Check for invalid labels if (label == "" || label.trimmed().isEmpty()) { throw Poco::InvalidArgumentException(); } // Check for duplicates IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { throw Poco::InvalidArgumentException(); } // Create descriptor. desc = new PerspectiveDescriptor(id, label, originalDescriptor.Cast()); this->Add(desc.Cast()); return desc; } void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) { PerspectiveDescriptor::Pointer desc = perspToRevert.Cast(); perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } PerspectiveRegistry::~PerspectiveRegistry() { // PlatformUI.getWorkbench().getExtensionTracker().unregisterHandler(this); // WorkbenchPlugin.getDefault().getPreferenceStore() .removePropertyChangeListener( // preferenceListener); } void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer /*desc*/) { //TODO Preferences // remove the entry from the preference store. //IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); /* * To delete the perspective definition from the preference store, use * the setToDefault method. Since no default is defined, this will * remove the entry */ //store.setToDefault(desc.getId() + PERSP); } bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer /*desc*/) const { //TODO Preferences //IPreferenceStore store = WorkbenchPlugin::GetDefault()->GetPreferenceStore(); //return store.contains(desc.getId() + PERSP); return false; } void PerspectiveRegistry::InitializePreferenceChangeListener() { // preferenceListener = new IPropertyChangeListener() // { // public void propertyChange(PropertyChangeEvent event) // { // /* // * To ensure the that no custom perspective definitions are // * deleted when preferences are imported, merge old and new // * values // */ // if (event.getProperty().endsWith(PERSP)) // { // /* A Perspective is being changed, merge */ // mergePerspectives(event); // } // else if (event.getProperty().equals( // IPreferenceConstants.PERSPECTIVES)) // { // /* The list of perpsectives is being changed, merge */ // updatePreferenceList((IPreferenceStore) event.getSource()); // } // } // // void MergePerspectives(PropertyChangeEvent::Pointer event) // { // IPreferenceStore store = (IPreferenceStore) event.getSource(); // if (event.getNewValue() == null // || event.getNewValue().equals("")) // { //$NON-NLS-1$ // /* // * Perpsective is being removed; if the user has deleted or // * reverted a custom perspective, let the change pass // * through. Otherwise, restore the custom perspective entry // */ // // // Find the matching descriptor in the registry // IPerspectiveDescriptor[] perspectiveList = getPerspectives(); // for (int i = 0; i < perspectiveList.length; i++) // { // QString id = perspectiveList[i].getId(); // if (event.getProperty().equals(id + PERSP)) // { // found // // descriptor // // see if the perspective has been flagged for // // reverting or deleting // if (!perspToRemove.contains(id)) // { // restore // store.setValue(id + PERSP, (QString) event // .getOldValue()); // } // else // { // remove element from the list // perspToRemove.remove(id); // } // } // } // } // else if ((event.getOldValue() == null || event.getOldValue() // .equals(""))) // { //$NON-NLS-1$ // // /* // * New perspective is being added, update the // * perspectiveRegistry to contain the new custom perspective // */ // // QString id = event.getProperty().substring(0, // event.getProperty().lastIndexOf(PERSP)); // if (findPerspectiveWithId(id) == null) // { // // perspective does not already exist in registry, add // // it // PerspectiveDescriptor desc = new PerspectiveDescriptor( // null, null, null); // StringReader reader = new StringReader((QString) event // .getNewValue()); // try // { // XMLMemento memento = XMLMemento // .createReadRoot(reader); // desc.restoreState(memento); // addPerspective(desc); // } // catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // /* If necessary, add to the list of perspectives */ // updatePreferenceList(store); // } // // void UpdatePreferenceList(IPreferenceStore store) // { // IPerspectiveDescriptor[] perspectiveList = getPerspectives(); // StringBuffer perspBuffer = new StringBuffer(); // for (int i = 0; i < perspectiveList.length; i++) // { // PerspectiveDescriptor desc = (PerspectiveDescriptor) perspectiveList[i]; // if (hasCustomDefinition(desc)) // { // perspBuffer.append(desc.getId()) // .append(SPACE_DELIMITER); // } // } // QString newList = perspBuffer.toString().trim(); // store.setValue(IPreferenceConstants.PERSPECTIVES, newList); // } // }; } void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc) { perspectives.push_back(desc); // IConfigurationElement::Pointer element = desc->GetConfigElement(); // if (element != 0) // { // PlatformUI::GetWorkbench().getExtensionTracker().registerObject( // element.getDeclaringExtension(), desc, IExtensionTracker.REF_WEAK); // } } void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } void PerspectiveRegistry::LoadCustom() { // Reader reader = null; // // /* Get the entries from the Preference store */ // IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); // // /* Get the space-delimited list of custom perspective ids */ // QString customPerspectives = store .getString( // IPreferenceConstants.PERSPECTIVES); // QString[] perspectivesList = StringConverter.asArray(customPerspectives); // // for (int i = 0; i < perspectivesList.length; i++) // { // try // { // QString xmlString = store.getString(perspectivesList[i] + PERSP); // if (xmlString != null && xmlString.length() != 0) // { // reader = new StringReader(xmlString); // } // // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // QString id = newPersp.getId(); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId(id); // if (oldPersp == null) // { // add(newPersp); // } // reader.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // // // Get the entries from files, if any // // if -data @noDefault specified the state location may not be // // initialized // IPath path = WorkbenchPlugin.getDefault().getDataLocation(); // if (path == null) // { // return; // } // // File folder = path.toFile(); // // if (folder.isDirectory()) // { // File[] fileList = folder.listFiles(); // int nSize = fileList.length; // for (int nX = 0; nX < nSize; nX++) // { // File file = fileList[nX]; // if (file.getName().endsWith(EXT)) // { // // get the memento // InputStream stream = null; // try // { // stream = new FileInputStream(file); // reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$ // // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId( // newPersp .getId()); // if (oldPersp == null) // { // add(newPersp); // } // // // save to the preference store // saveCustomPersp(newPersp, memento); // // // delete the file // file.delete(); // // reader.close(); // stream.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // } } void PerspectiveRegistry::UnableToLoadPerspective(const QString& status) { QString msg = "Unable to load perspective"; if (status == "") { WorkbenchPlugin::Log(msg); //IStatus errStatus = // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } else { WorkbenchPlugin::Log(status + ": " + msg); //IStatus errStatus = StatusUtil.newStatus(status, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } } void PerspectiveRegistry::LoadPredefined() { PerspectiveRegistryReader reader; reader.ReadPerspectives(this); } void PerspectiveRegistry::VerifyDefaultPerspective() { // Step 1: Try current defPerspId value. IPerspectiveDescriptor::Pointer desc; if (defaultPerspID != "") { desc = this->FindPerspectiveWithId(defaultPerspID); } if (desc != 0) { return; } // Step 2. Read default value. //TODO Preferences // QString str = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID); // if (str != null && str.length() > 0) // { // desc = this->FindPerspectiveWithId(str); // } // if (desc != 0) // { // defaultPerspID = str; // return; // } // Step 3. Use application-specific default defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp index 8b21e35f52..d6b0b82476 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp @@ -1,346 +1,346 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryQtStyleManager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "berryQtPreferences.h" #include "berryWorkbenchPlugin.h" namespace berry { QtStyleManager::QtStyleManager() { AddDefaultStyle(); ReadPreferences(); } void QtStyleManager::ReadPreferences() { IPreferencesService* prefService = WorkbenchPlugin::GetDefault()->GetPreferencesService(); IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); QString paths = stylePref->Get(QtPreferences::QT_STYLE_SEARCHPATHS, ""); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddStyles(it.next()); } QString styleName = stylePref->Get(QtPreferences::QT_STYLE_NAME, ""); // if a style is contributed via the Qt resource mechanism, it may not be // registered yet. if (Contains(styleName)) // do not update the style in the QApplication instance, // since it might not be created yet SetStyle(styleName, false); else SetDefaultStyle(false); } QtStyleManager::~QtStyleManager() { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) { delete i.value(); } } void QtStyleManager::AddDefaultStyle() { #ifndef _APPLE_ AddStyle(":/org.blueberry.ui.qt/defaultstyle.qss", "Default"); defaultStyle = styles[":/org.blueberry.ui.qt/defaultstyle.qss"]; #endif } void QtStyleManager::ClearStyles() { for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end(); ) { if (!i.value()->fileName.startsWith(':')) { delete i.value(); i = styles.erase(i); } else ++i; } SetDefaultStyle(); } QtStyleManager::Style QtStyleManager::GetStyle() const { return Style(currentStyle->name, currentStyle->fileName); } QString QtStyleManager::GetStylesheet() const { return currentStyle->stylesheet; } QString QtStyleManager::GetActiveTabStylesheet() const { return currentStyle->activeTabStylesheet; } QString QtStyleManager::GetTabStylesheet() const { return currentStyle->tabStylesheet; } void QtStyleManager::AddStyle(const QString& styleFileName, const QString& styleName) { ExtStyle* newStyle = new ExtStyle(); if (styleName.isEmpty()) { QFileInfo info(styleFileName); newStyle->name = info.completeBaseName(); } else { newStyle->name = styleName; } newStyle->fileName = styleFileName; styles.insert(newStyle->fileName, newStyle); } void QtStyleManager::AddStyles(const QString& path) { QDirIterator dirIt(path); while (dirIt.hasNext()) { QString current = dirIt.next(); QFileInfo info = dirIt.fileInfo(); if (info.isFile() && info.isReadable()) { QString fileName = info.fileName(); if (fileName.endsWith("-tab.qss") || fileName.endsWith("-activetab.qss")) continue; if (fileName.endsWith(".qss")) AddStyle(current); } } } void QtStyleManager::ReadStyleData(ExtStyle* style) { QString tabStyleFileName(style->fileName); QString activeTabStyleFileName(style->fileName); int index = style->fileName.lastIndexOf(".qss"); tabStyleFileName.replace(index, 4, "-tab.qss"); activeTabStyleFileName.replace(index, 4, "-activetab.qss"); QFile styleFile(style->fileName); if (styleFile.open(QIODevice::ReadOnly)) { QTextStream in(&styleFile); style->stylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << style->fileName.toStdString(); } QFile tabStyleFile(tabStyleFileName); if (tabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&tabStyleFile); style->tabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << tabStyleFileName.toStdString(); } QFile activeTabStyleFile(activeTabStyleFileName); if (activeTabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&activeTabStyleFile); style->activeTabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << activeTabStyleFileName.toStdString(); } } void QtStyleManager::RemoveStyle(const QString& styleFileName) { if (currentStyle->fileName == styleFileName) { SetDefaultStyle(); } delete styles.take(styleFileName); } void QtStyleManager::RemoveStyles(const QString& repo) { if (repo.isEmpty()) { ClearStyles(); return; } for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end();) { ExtStyle* style = i.value(); QFileInfo info(style->fileName); if (info.absolutePath() == repo) { if (style->name == currentStyle->name) { SetDefaultStyle(); } i = styles.erase(i); delete style; } else { ++i; } } } void QtStyleManager::GetStyles(StyleList& styleNames) const { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) styleNames.push_back(Style(i.value()->name, i.value()->fileName)); } void QtStyleManager::GetIconThemes(IconThemeList& iconThemes) const { iconThemes.clear(); iconThemes.push_back(IconTheme(QString( "<>" ))); QStringList iconSearchPaths = QIcon::themeSearchPaths(); for(QStringList::Iterator pathIt = iconSearchPaths.begin(); pathIt != iconSearchPaths.end(); ++pathIt) { QDirIterator dirIt(*pathIt); while (dirIt.hasNext()) { QString current = dirIt.next(); QFileInfo info = dirIt.fileInfo(); if (info.isDir() && info.isReadable()) { QFileInfo themeFile( info.filePath() + QString("/index.theme") ); if( themeFile.exists() && themeFile.isFile() && themeFile.isReadable() ) { QString fileName = info.fileName(); iconThemes.push_back( IconTheme(fileName) ); } } } } } void QtStyleManager::SetStyle(const QString& fileName) { SetStyle(fileName, true); } void QtStyleManager::SetStyle(const QString& fileName, bool update) { if (fileName.isEmpty()) { SetDefaultStyle(); return; } FileNameToStyleMap::const_iterator i = styles.find(fileName); ExtStyle* style = 0; if (i == styles.end()) { BERRY_WARN << "Style " + fileName.toStdString() << " does not exist"; style = defaultStyle; } else { style = i.value(); } currentStyle = style; ReadStyleData(style); if (update) { qApp->setStyleSheet(currentStyle->stylesheet); PlatformUI::GetWorkbench()->UpdateTheme(); } } void QtStyleManager::SetIconTheme(const QString& themeName) { if( themeName == QString( "<>" ) ) { SetIconTheme( QString("tango"), true); } else { SetIconTheme(themeName, true); } } -void QtStyleManager::SetIconTheme(const QString& themeName, bool update) +void QtStyleManager::SetIconTheme(const QString& themeName, bool /*update*/) { QIcon::setThemeName( themeName ); } QtStyleManager::Style QtStyleManager::GetDefaultStyle() const { return Style(defaultStyle->name, defaultStyle->fileName); } void QtStyleManager::SetDefaultStyle() { SetDefaultStyle(true); } void QtStyleManager::SetDefaultStyle(bool update) { SetStyle(defaultStyle->fileName, update); } bool QtStyleManager::Contains(const QString& fileName) const { return styles.contains(fileName); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp index 18cedf8bda..7f8a7186c3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp @@ -1,247 +1,247 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryQtStylePreferencePage.h" #include #include #include "berryWorkbenchPlugin.h" #include #include namespace berry { QtStylePreferencePage::QtStylePreferencePage() { } void QtStylePreferencePage::Init(IWorkbench::Pointer ) { } void QtStylePreferencePage::CreateQtControl(QWidget* parent) { mainWidget = new QWidget(parent); controls.setupUi(mainWidget); berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference(); if (styleManagerRef) { styleManager = context->getService(styleManagerRef); } m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); Update(); connect(controls.m_StylesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(StyleChanged(int))); connect(controls.m_IconThemeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(IconThemeChanged(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); 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::FillIconThemeComboBox(const QString currentIconTheme) { controls.m_IconThemeComboBox->clear(); berry::IQtStyleManager::IconThemeList iconThemes; styleManager->GetIconThemes(iconThemes); qSort(iconThemes); for (int i = 0; i < iconThemes.size(); ++i) { controls.m_IconThemeComboBox->addItem(iconThemes.at(i).name); } QString currentTheme = currentIconTheme; if(currentTheme == QString("")) { currentTheme = QString("<>"); } controls.m_IconThemeComboBox->setCurrentIndex(iconThemes.indexOf( currentTheme )); } 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::IconThemeChanged(int /*index*/) { QString themeName = controls.m_IconThemeComboBox->currentText(); styleManager->SetIconTheme(themeName); } 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() { m_StylePref->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString()); QString paths; for (int i = 0; i < controls.m_PathList->count(); ++i) { QString path = controls.m_PathList->item(i)->text() + ";"; paths += path; } QString currentTheme = QIcon::themeName(); if(currentTheme.isEmpty()) { currentTheme = QString("<>"); } m_StylePref->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths); m_StylePref->Put(berry::QtPreferences::QT_ICON_THEME, currentTheme); return true; } void QtStylePreferencePage::PerformCancel() { Update(); } void QtStylePreferencePage::Update() { styleManager->RemoveStyles(); QString paths = m_StylePref->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, ""); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddPath(it.next(), false); } - QString iconTheme = QString::fromStdString(m_StylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>")); + QString iconTheme = m_StylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>"); styleManager->SetIconTheme( iconTheme ); QString name = m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, ""); styleManager->SetStyle(name); oldStyle = styleManager->GetStyle(); FillStyleCombo(oldStyle); FillIconThemeComboBox( iconTheme ); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp index a0af8e075d..a23f9b1783 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp @@ -1,222 +1,218 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryViewDescriptor.h" #include "berryIConfigurationElement.h" #include "berryCoreException.h" #include "berryIExtension.h" #include "berryIContributor.h" #include "berryStatus.h" #include "berryRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" #include "berryImageDescriptor.h" #include "berryAbstractUICTKPlugin.h" #include "berryImageDescriptor.h" #include "handlers/berryIHandlerActivation.h" namespace berry { ViewDescriptor::ViewDescriptor(const IConfigurationElement::Pointer& e) : configElement(e) { this->LoadFromExtension(); } IViewPart::Pointer ViewDescriptor::CreateView() { IViewPart::Pointer part(configElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return part; } -const QList& ViewDescriptor::GetCategoryPath() const +QStringList ViewDescriptor::GetCategoryPath() const { return categoryPath; } IConfigurationElement::Pointer ViewDescriptor::GetConfigurationElement() const { return configElement; } QString ViewDescriptor::GetDescription() const { return RegistryReader::GetDescription(configElement); } QString ViewDescriptor::GetId() const { return id; } bool ViewDescriptor::operator==(const Object* o) const { if (const IViewDescriptor* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } ImageDescriptor::Pointer ViewDescriptor::GetImageDescriptor() const { if (imageDescriptor) { return imageDescriptor; } QString iconName = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); // If the icon attribute was omitted, use the default one if (iconName.isEmpty()) { //TODO default image descriptor //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); return ImageDescriptor::GetMissingImageDescriptor(); } IExtension::Pointer extension(configElement->GetDeclaringExtension()); const QString extendingPluginId(extension->GetContributor()->GetName()); imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); if (!imageDescriptor) { // Try legacy BlueBerry method imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); } // If the icon attribute was invalid, use the error icon if (!imageDescriptor) { imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); } return imageDescriptor; } QString ViewDescriptor::GetLabel() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString ViewDescriptor::GetAccelerator() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ACCELERATOR); } bool ViewDescriptor::GetAllowMultiple() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE).compare("true", Qt::CaseInsensitive) == 0; } bool ViewDescriptor::IsRestorable() const { QString str = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_RESTORABLE); return str.isNull() ? true : str.compare("true", Qt::CaseInsensitive) == 0; } Object* ViewDescriptor::GetAdapter(const QString& adapter) { if (adapter == qobject_interface_iid()) { return GetConfigurationElement().GetPointer(); } return NULL; } void ViewDescriptor::ActivateHandler() { //TODO ViewDescriptor handler activation // if (!handlerActivation) // { // IHandler::Pointer handler(new ShowViewHandler(this->GetId())); // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerActivation = handlerService // ->ActivateHandler(this->GetId(), handler); // } } void ViewDescriptor::DeactivateHandler() { //TODO ViewDescriptor handler deactivation // if (handlerActivation) // { // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerService->DeactivateHandler(handlerActivation); // handlerActivation = 0; // } } -std::vector< std::string> ViewDescriptor::GetKeywordReferences() const +QStringList ViewDescriptor::GetKeywordReferences() const { - std::vector result; - std::string keywordRefId; - std::vector keywordRefs; - berry::IConfigurationElement::vector::iterator keywordRefsIt; - keywordRefs = configElement->GetChildren("keywordReference"); - for (keywordRefsIt = keywordRefs.begin() - ; keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs + QStringList result; + auto keywordRefs = configElement->GetChildren("keywordReference"); + for (auto keywordRefsIt = keywordRefs.begin(); + keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { - (*keywordRefsIt)->GetAttribute("id", keywordRefId); - result.push_back(keywordRefId); + result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString ViewDescriptor::GetPluginId() const { return configElement->GetContributor()->GetName(); } QString ViewDescriptor::GetLocalId() const { return this->GetId(); } void ViewDescriptor::LoadFromExtension() { id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); // Sanity check. QString name = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); if (name.isEmpty() || RegistryReader::GetClassValue(configElement, WorkbenchRegistryConstants::ATT_CLASS).isEmpty()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, configElement->GetContributor()->GetName(), 0, QString("Invalid extension (missing label or class name): ") + id)); throw CoreException(status); } QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); if (!category.isEmpty()) { // Parse the path tokens and store them foreach (QString pathElement, category.split('/', QString::SkipEmptyParts)) { if (!pathElement.trimmed().isEmpty()) { categoryPath.push_back(pathElement.trimmed()); } } } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h index e63af84b04..80c18f0f76 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h @@ -1,164 +1,163 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYVIEWDESCRIPTOR_H_ #define BERRYVIEWDESCRIPTOR_H_ #include "berryIViewPart.h" #include "berryIViewDescriptor.h" #include "berryIPluginContribution.h" -#include -#include +#include namespace berry { struct IConfigurationElement; struct IHandlerActivation; /** * \ingroup org_blueberry_ui_internal * */ class ViewDescriptor : public IViewDescriptor, public IPluginContribution { private: QString id; mutable SmartPointer imageDescriptor; IConfigurationElement::Pointer configElement; - QList categoryPath; + QStringList categoryPath; /** * The activation token returned when activating the show view handler with * the workbench. */ SmartPointer handlerActivation; public: berryObjectMacro(ViewDescriptor); /** * Create a new ViewDescriptor for an extension. * * @param e the configuration element * @throws CoreException thrown if there are errors in the configuration */ ViewDescriptor(const SmartPointer& e); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#createView() */ IViewPart::Pointer CreateView(); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getCategoryPath() */ - const QList& GetCategoryPath() const; + QStringList GetCategoryPath() const; /** * Return the configuration element for this descriptor. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getDescription() */ QString GetDescription() const; - std::vector GetKeywordReferences() const; + QStringList GetKeywordReferences() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getId() */ QString GetId() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getImageDescriptor() */ SmartPointer GetImageDescriptor() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getLabel() */ QString GetLabel() const; /** * Return the accelerator attribute. * * @return the accelerator attribute */ QString GetAccelerator() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getAllowMultiple() */ bool GetAllowMultiple() const; /* (non-Javadoc) * @see org.eclipse.ui.views.IViewDescriptor#getRestorable() */ bool IsRestorable() const; bool operator==(const Object*) const; /** * Activates a show view handler for this descriptor. This handler can later * be deactivated by calling {@link ViewDescriptor#deactivateHandler()}. * This method will only activate the handler if it is not currently active. * */ void ActivateHandler(); /** * Deactivates the show view handler for this descriptor. This handler was * previously activated by calling {@link ViewDescriptor#activateHandler()}. * This method will only deactivative the handler if it is currently active. * */ void DeactivateHandler(); /* * @see IPluginContribution#GetPluginId() */ QString GetPluginId() const; /* * @see IPluginContribution#GetLocalId() */ QString GetLocalId() const; protected: /* (non-Javadoc) * @see IAdaptable#GetAdapterImpl(const std::type_info&) */ Object* GetAdapter(const QString& adapter); private: /** * load a view descriptor from the registry. */ void LoadFromExtension(); }; } #endif /*BERRYVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp index 30823b0e33..e68c290110 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp @@ -1,4113 +1,4113 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryLog.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartSite.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPerspective.h" #include "berryLayoutPartSash.h" #include "berryWorkbenchPlugin.h" #include "berryEditorAreaHelper.h" #include "berrySaveablesList.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTreeNode.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartService.h" #include "berryStickyViewManager.h" #include "intro/berryIntroConstants.h" #include "intro/berryViewIntroAdapterPart.h" #include "dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" #include "berryUIException.h" #include "berryPlatformUI.h" #include "berryPartPane.h" #include "berryImageDescriptor.h" #include namespace berry { WorkbenchPage::ActivationOrderPred::ActivationOrderPred( WorkbenchPage::ActivationList* al) : activationList(al) { } bool WorkbenchPage::ActivationOrderPred::operator()( const IViewReference::Pointer o1, const IViewReference::Pointer o2) const { WorkbenchPage::ActivationList::PartListIter pos1 = activationList->IndexOf( o1.Cast ()); WorkbenchPage::ActivationList::PartListIter pos2 = activationList->IndexOf( o2.Cast ()); return pos1 < pos2; } void WorkbenchPage::PerspectiveList::UpdateActionSets( Perspective::Pointer /*oldPersp*/, Perspective::Pointer /*newPersp*/) { //TODO WorkbenchPage action sets // // Update action sets // // IContextService service = (IContextService) window // .getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // if (newPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = newPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.showAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = newPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.maskAction(descriptor); // } // } // // if (oldPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = oldPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.hideAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = oldPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.unmaskAction(descriptor); // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } } WorkbenchPage::PerspectiveList::PerspectiveList() { } void WorkbenchPage::PerspectiveList::Reorder( IPerspectiveDescriptor::Pointer perspective, int newLoc) { PerspectiveListType::iterator oldLocation = openedList.end(); Perspective::Pointer movedPerspective; for (PerspectiveListType::iterator iterator = openedList.begin(); iterator != openedList.end(); ++iterator) { Perspective::Pointer openPerspective = *iterator; if (openPerspective->GetDesc() == perspective) { oldLocation = std::find(openedList.begin(), openedList.end(), openPerspective); movedPerspective = openPerspective; } } PerspectiveListType::iterator newLocation = openedList.begin(); for (int i = 0; i < newLoc; ++i, ++newLocation) ; if (oldLocation == newLocation) { return; } openedList.erase(oldLocation); openedList.insert(newLocation, movedPerspective); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetSortedPerspectives() { return usedList; } bool WorkbenchPage::PerspectiveList::Add(Perspective::Pointer perspective) { openedList.push_back(perspective); usedList.push_front(perspective); //It will be moved to top only when activated. return true; } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::Begin() { return openedList.begin(); } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::End() { return openedList.end(); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetOpenedPerspectives() { return openedList; } bool WorkbenchPage::PerspectiveList::Remove(Perspective::Pointer perspective) { if (active == perspective) { this->UpdateActionSets(active, Perspective::Pointer(0)); active = 0; } usedList.removeAll(perspective); PerspectiveListType::size_type origSize = openedList.size(); openedList.removeAll(perspective); return openedList.size() != origSize; } void WorkbenchPage::PerspectiveList::Swap(Perspective::Pointer oldPerspective, Perspective::Pointer newPerspective) { PerspectiveListType::iterator oldIter = std::find(openedList.begin(), openedList.end(), oldPerspective); PerspectiveListType::iterator newIter = std::find(openedList.begin(), openedList.end(), newPerspective); if (oldIter == openedList.end() || newIter == openedList.end()) { return; } std::iter_swap(oldIter, newIter); } bool WorkbenchPage::PerspectiveList::IsEmpty() { return openedList.empty(); } Perspective::Pointer WorkbenchPage::PerspectiveList::GetActive() { return active; } Perspective::Pointer WorkbenchPage::PerspectiveList::GetNextActive() { if (active == 0) { if (usedList.empty()) { return Perspective::Pointer(0); } else { return usedList.back(); } } else { if (usedList.size() < 2) { return Perspective::Pointer(0); } else { return *(--usedList.end()); } } } WorkbenchPage::PerspectiveList::PerspectiveListType::size_type WorkbenchPage::PerspectiveList::Size() { return openedList.size(); } void WorkbenchPage::PerspectiveList::SetActive(Perspective::Pointer perspective) { if (perspective == active) { return; } this->UpdateActionSets(active, perspective); active = perspective; if (perspective != 0) { usedList.removeAll(perspective); usedList.push_back(perspective); } } WorkbenchPage::ActivationList::ActivationList(WorkbenchPage* page) : page(page) { } void WorkbenchPage::ActivationList::SetActive(SmartPointer part) { if (parts.empty()) { return; } IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref) { if (ref == parts.back()) { return; } parts.erase(std::find(parts.begin(), parts.end(), ref)); parts.push_back(ref); } } void WorkbenchPage::ActivationList::BringToTop(SmartPointer< IWorkbenchPartReference> ref) { ILayoutContainer::Pointer targetContainer(page->GetContainer(ref)); PartListIter newIndex = this->LastIndexOfContainer(targetContainer); if (newIndex != parts.end() && ref == *newIndex) { return; } if (newIndex == parts.end()) { parts.push_back(ref); } else { PartListType::size_type index = newIndex - parts.begin(); parts.erase(std::find(parts.begin(), parts.end(), ref)); PartListIter insertIndex = parts.begin() + index; parts.insert(insertIndex, ref); } } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::LastIndexOfContainer( SmartPointer container) { PartListReverseIter i = parts.rbegin(); while (i != parts.rend()) { IWorkbenchPartReference::Pointer ref(*i); ILayoutContainer::Pointer cnt(page->GetContainer(ref)); if (cnt == container) { return --i.base(); } ++i; } return parts.end(); } void WorkbenchPage::ActivationList::SetActive(SmartPointer< IWorkbenchPartReference> ref) { this->SetActive(ref->GetPart(true)); } void WorkbenchPage::ActivationList::Add( SmartPointer ref) { if (std::find(parts.begin(), parts.end(), ref) != parts.end()) { return; } ref->GetPart(false); parts.push_front(ref); } SmartPointer WorkbenchPage::ActivationList::GetActive() { if (parts.empty()) { return IWorkbenchPart::Pointer(0); } return this->GetActive(parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetPreviouslyActive() { if (parts.size() < 2) { return IWorkbenchPart::Pointer(0); } return this->GetActive(--parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( bool editorsOnly) { return this->GetActiveReference(parts.end(), editorsOnly); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer part) { IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref == 0) { return parts.end(); } return std::find(parts.begin(), parts.end(), ref); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer ref) { return std::find(parts.begin(), parts.end(), ref); } bool WorkbenchPage::ActivationList::Remove( SmartPointer ref) { bool contains = std::find(parts.begin(), parts.end(), ref) != parts.end(); parts.erase(std::find(parts.begin(), parts.end(), ref)); return contains; } SmartPointer WorkbenchPage::ActivationList::GetTopEditor() { IEditorReference::Pointer editor = this->GetActiveReference(parts.end(), true).Cast (); if (editor == 0) { return IEditorPart::Pointer(0); } return editor->GetEditor(true); } SmartPointer WorkbenchPage::ActivationList::GetActive( PartListIter start) { IWorkbenchPartReference::Pointer ref(this->GetActiveReference(start, false)); if (!ref) { return IWorkbenchPart::Pointer(0); } return ref->GetPart(true); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly) { // First look for parts that aren't obscured by the current zoom state IWorkbenchPartReference::Pointer nonObscured = this->GetActiveReference( start, editorsOnly, true); if (nonObscured) { return nonObscured; } // Now try all the rest of the parts return this->GetActiveReference(start, editorsOnly, false); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly, bool /*skipPartsObscuredByZoom*/) { QList views = page->GetViewReferences(); PartListReverseIter i(start); while (i != parts.rend()) { WorkbenchPartReference::Pointer ref(i->Cast ()); if (editorsOnly && (ref.Cast () == 0)) { ++i; continue; } // Skip parts whose containers have disabled auto-focus PartPane::Pointer pane(ref->GetPane()); if (pane) { if (!pane->AllowsAutoFocus()) { ++i; continue; } // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } } // Skip fastviews (unless overridden) if (IViewReference::Pointer viewRef = ref.Cast()) { //if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { for (int j = 0; j < views.size(); j++) { if (views[j] == viewRef) { return viewRef.Cast (); } } //} } else { return ref.Cast (); } ++i; } return IWorkbenchPartReference::Pointer(0); } QList > WorkbenchPage::ActivationList::GetEditors() { QList editors; for (PartListIter i = parts.begin(); i != parts.end(); ++i) { if (IEditorReference::Pointer part = i->Cast()) { editors.push_back(part); } } return editors; } QList > WorkbenchPage::ActivationList::GetParts() { QList views(page->GetViewReferences()); QList resultList; for (PartListIter iterator = parts.begin(); iterator != parts.end(); ++iterator) { if (IViewReference::Pointer ref = iterator->Cast()) { //Filter views from other perspectives for (int i = 0; i < views.size(); i++) { if (ref == views[i]) { resultList.push_back(ref); break; } } } else { resultList.push_back(*iterator); } } return resultList; } void WorkbenchPage::ActionSwitcher::UpdateActivePart( IWorkbenchPart::Pointer newPart) { IWorkbenchPart::Pointer _activePart = this->activePart.Lock(); IEditorPart::Pointer _topEditor = this->topEditor.Lock(); if (_activePart == newPart) { return; } bool isNewPartAnEditor = newPart.Cast ().IsNotNull(); if (isNewPartAnEditor) { QString oldId; if (_topEditor) { oldId = _topEditor->GetSite()->GetId(); } QString newId = newPart->GetSite()->GetId(); // if the active part is an editor and the new editor // is the same kind of editor, then we don't have to do // anything if (activePart == topEditor && newId == oldId) { activePart = newPart; topEditor = newPart.Cast (); return; } // remove the contributions of the old editor // if it is a different kind of editor if (oldId != newId) { this->DeactivateContributions(_topEditor, true); } // if a view was the active part, disable its contributions if (_activePart && _activePart != _topEditor) { this->DeactivateContributions(_activePart, true); } // show (and enable) the contributions of the new editor // if it is a different kind of editor or if the // old active part was a view if (newId != oldId || _activePart != _topEditor) { this->ActivateContributions(newPart, true); } } else if (newPart.IsNull()) { if (_activePart) { // remove all contributions this->DeactivateContributions(_activePart, true); } } else { // new part is a view // if old active part is a view, remove all contributions, // but if old part is an editor only disable if (_activePart) { this->DeactivateContributions(_activePart, _activePart.Cast ().IsNotNull()); } this->ActivateContributions(newPart, true); } //TODO WorkbenchPage action sets // ArrayList newActionSets = 0; // if (isNewPartAnEditor || (activePart == topEditor && newPart == 0)) // { // newActionSets = calculateActionSets(newPart, 0); // } // else // { // newActionSets = calculateActionSets(newPart, topEditor); // } // // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } if (isNewPartAnEditor) { topEditor = newPart.Cast (); } else if (activePart == topEditor && newPart.IsNull()) { // since we removed all the contributions, we clear the top // editor topEditor.Reset(); } activePart = newPart; } void WorkbenchPage::ActionSwitcher::UpdateTopEditor( IEditorPart::Pointer newEditor) { if (topEditor.Lock() == newEditor) { return; } if (activePart == topEditor) { this->UpdateActivePart(newEditor); return; } QString oldId; if (!topEditor.Expired()) { oldId = topEditor.Lock()->GetSite()->GetId(); } QString newId; if (newEditor.IsNotNull()) { newId = newEditor->GetSite()->GetId(); } if (oldId == newId) { // we don't have to change anything topEditor = newEditor; return; } // Remove the contributions of the old editor if (!topEditor.Expired()) { this->DeactivateContributions(topEditor.Lock(), true); } // Show (disabled) the contributions of the new editor if (newEditor.IsNotNull()) { this->ActivateContributions(newEditor, false); } // ArrayList newActionSets = calculateActionSets(activePart, newEditor); // if (!updateActionSets(newActionSets)) // { // updateActionBars(); // } topEditor = newEditor; } void WorkbenchPage::ActionSwitcher::ActivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*enable*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->ActivateActionBars(enable); } void WorkbenchPage::ActionSwitcher::DeactivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*remove*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->DeactivateActionBars(remove); } IExtensionPoint::Pointer WorkbenchPage::GetPerspectiveExtensionPoint() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input) { if (layoutID == "") { throw WorkbenchException("Perspective ID is undefined"); } this->Register(); this->Init(w, layoutID, input, true); this->UnRegister(false); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, IAdaptable* input) { this->Register(); this->Init(w, "", input, false); this->UnRegister(false); } void WorkbenchPage::Activate(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } if (window->IsClosing()) { return; } // if (composite!=0 && composite.isVisible() && !((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // Activate part. //if (window.getActivePage() == this) { IWorkbenchPartReference::Pointer ref = this->GetReference(part); this->InternalBringToTop(ref); this->SetActivePart(part); } void WorkbenchPage::ActivatePart(const IWorkbenchPart::Pointer part) { // Platform.run(new SafeRunnable(WorkbenchMessages.WorkbenchPage_ErrorActivatingView) // { // public void WorkbenchPage::run() // { if (part.IsNotNull()) { //part.setFocus(); PartPane::Pointer pane = this->GetPane(part); pane->SetFocus(); PartSite::Pointer site = part->GetSite().Cast (); pane->ShowFocus(true); //this->UpdateTabList(part); //SubActionBars bars = (SubActionBars) site.getActionBars(); //bars.partChanged(part); } // } // } // ); } void WorkbenchPage::AddPartListener(IPartListener* l) { partList->GetPartService()->AddPartListener(l); } void WorkbenchPage::AddSelectionListener(ISelectionListener* listener) { selectionService->AddSelectionListener(listener); } void WorkbenchPage::AddSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddSelectionListener(partId, listener); } void WorkbenchPage::AddPostSelectionListener( ISelectionListener* listener) { selectionService->AddPostSelectionListener(listener); } void WorkbenchPage::AddPostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddPostSelectionListener(partId, listener); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPartReference::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPart::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return this->GetPane(this->GetReference(part)); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPartReference::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return part.Cast ()->GetPane(); } bool WorkbenchPage::InternalBringToTop(IWorkbenchPartReference::Pointer part) { bool broughtToTop = false; // Move part. if (part.Cast ().IsNotNull()) { ILayoutContainer::Pointer container = this->GetContainer(part); if (container.Cast () != 0) { PartStack::Pointer stack = container.Cast (); PartPane::Pointer newPart = this->GetPane(part); if (stack->GetSelection() != newPart) { stack->SetSelection(newPart); } broughtToTop = true; } } else if (part.Cast ().IsNotNull()) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { broughtToTop = persp->BringToTop(part.Cast ()); } } // Ensure that this part is considered the most recently activated part // in this stack activationList->BringToTop(part); return broughtToTop; } void WorkbenchPage::BringToTop(IWorkbenchPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return; } // if (!((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // QString label; // debugging only // if (UIStats.isDebugging(UIStats.BRING_PART_TO_TOP)) // { // label = part != 0 ? part.getTitle() : "none"; //$NON-NLS-1$ // } IWorkbenchPartReference::Pointer ref = this->GetReference(part); ILayoutContainer::Pointer activeEditorContainer = this->GetContainer( this->GetActiveEditor().Cast ()); ILayoutContainer::Pointer activePartContainer = this->GetContainer( this->GetActivePart()); ILayoutContainer::Pointer newPartContainer = this->GetContainer(part); if (newPartContainer == activePartContainer) { this->MakeActive(ref); } else if (newPartContainer == activeEditorContainer) { if (ref.Cast () != 0) { if (part != 0) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () != 0) { ref = site.Cast ()->GetPane()->GetPartReference(); } } this->MakeActiveEditor(ref.Cast ()); } else { this->MakeActiveEditor(IEditorReference::Pointer(0)); } } else { this->InternalBringToTop(ref); if (ref != 0) { partList->FirePartBroughtToTop(ref); } } } void WorkbenchPage::BusyResetPerspective() { ViewIntroAdapterPart::Pointer introViewAdapter = dynamic_cast (GetWorkbenchWindow() ->GetWorkbench()->GetIntroManager())->GetIntroAdapterPart().Cast< ViewIntroAdapterPart> (); // PartPane introPane = 0; // boolean introFullScreen = false; // if (introViewAdapter != 0) // { // introPane = ((PartSite) introViewAdapter.getSite()).getPane(); // introViewAdapter.setHandleZoomEvents(false); // introFullScreen = introPane.isZoomed(); // } // //try to prevent intro flicker. // if (introFullScreen) // { // window.getShell().setRedraw(false); // } // try // { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } // Get the current perspective. // This describes the working layout of the page and differs from // the original template. Perspective::Pointer oldPersp = this->GetActivePerspective(); // Map the current perspective to the original template. // If the original template cannot be found then it has been deleted. // In that case just return. (PR#1GDSABU). IPerspectiveRegistry* reg = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry(); PerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId( oldPersp->GetDesc()->GetId()).Cast (); if (desc == 0) { desc = reg->FindPerspectiveWithId(oldPersp ->GetDesc().Cast< PerspectiveDescriptor> ()->GetOriginalId()).Cast< PerspectiveDescriptor> (); } if (desc == 0) { return; } // Notify listeners that we are doing a reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET); // Create new persp from original template. // Suppress the perspectiveOpened and perspectiveClosed events otherwise it looks like two // instances of the same perspective are open temporarily (see bug 127470). Perspective::Pointer newPersp = this->CreatePerspective(desc, false); if (newPersp == 0) { // We're not going through with the reset, so it is complete. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); return; } // Update the perspective list and shortcut perspList.Swap(oldPersp, newPersp); // Install new persp. this->SetPerspective(newPersp); // Destroy old persp. this->DisposePerspective(oldPersp, false); // Update the Coolbar layout. this->ResetToolBarLayout(); // restore the maximized intro if (introViewAdapter) { try { // ensure that the intro is visible in the new perspective ShowView(IntroConstants::INTRO_VIEW_ID); // if (introFullScreen) // { // toggleZoom(introPane.getPartReference()); // } } catch (PartInitException& e) { //TODO IStatus WorkbenchPlugin::Log("Could not restore intro", e); // WorkbenchPlugin.getStatus(e)); } // finally // { // // we want the intro back to a normal state before we fire the event // introViewAdapter.setHandleZoomEvents(true); // } } // Notify listeners that we have completed our reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); // } // finally // { // // reset the handling of zoom events (possibly for the second time) in case there was // // an exception thrown // if (introViewAdapter != 0) // { // introViewAdapter.setHandleZoomEvents(true); // } // // if (introFullScreen) // { // window.getShell().setRedraw(true); // } // } } void WorkbenchPage::RemovePerspective(IPerspectiveDescriptor::Pointer desc) { Perspective::Pointer newPersp; PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(desc); perspList.Remove(newPersp); } void WorkbenchPage::BusySetPerspective(IPerspectiveDescriptor::Pointer desc) { // Create new layout. QString label = desc->GetId(); // debugging only Perspective::Pointer newPersp; //try //{ //UIStats.start(UIStats.SWITCH_PERSPECTIVE, label); PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(realDesc); if (newPersp == 0) { newPersp = this->CreatePerspective(realDesc, true); if (newPersp == 0) { return; } } // Change layout. this->SetPerspective(newPersp); // } // catch (std::exception& e) // { // UIStats.end(UIStats.SWITCH_PERSPECTIVE, desc.getId(), label); // throw e; // } } IViewPart::Pointer WorkbenchPage::BusyShowView(const QString& viewID, const QString& secondaryID, int mode) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewPart::Pointer(0); } // If this view is already visible just return. IViewReference::Pointer ref = persp->FindView(viewID, secondaryID); IViewPart::Pointer view; if (ref != 0) { view = ref->GetView(true); } if (view != 0) { this->BusyShowView(view, mode); return view; } // Show the view. view = persp->ShowView(viewID, secondaryID); if (view != 0) { this->BusyShowView(view, mode); IWorkbenchPartReference::Pointer partReference = this->GetReference(view); PartPane::Pointer partPane = this->GetPane(partReference); partPane->SetInLayout(true); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, GetPerspective(), partReference, CHANGE_VIEW_SHOW); window->FirePerspectiveChanged(thisPage, GetPerspective(), CHANGE_VIEW_SHOW); } return view; } void WorkbenchPage::BusyShowView(IViewPart::Pointer part, int mode) { // if (!((GrabFocus) Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } if (mode == VIEW_ACTIVATE) { this->Activate(part); } else if (mode == VIEW_VISIBLE) { IWorkbenchPartReference::Pointer ref = this->GetActivePartReference(); // if there is no active part or it's not a view, bring to top if (ref == 0 || ref.Cast () == 0) { this->BringToTop(part); } else { // otherwise check to see if the we're in the same stack as the active view IViewReference::Pointer activeView = ref.Cast (); QList viewStack = this->GetViewReferenceStack(part); for (int i = 0; i < viewStack.size(); i++) { if (viewStack[i] == activeView) { return; } } this->BringToTop(part); } } } bool WorkbenchPage::CertifyPart(IWorkbenchPart::Pointer part) { //Workaround for bug 22325 if (part != 0 && part->GetSite().Cast () == 0) { return false; } if (part.Cast () != 0) { IEditorReference::Pointer ref = this->GetReference(part).Cast< IEditorReference> (); return ref != 0 && this->GetEditorManager()->ContainsEditor(ref); } if (part.Cast () != 0) { Perspective::Pointer persp = this->GetActivePerspective(); return persp != 0 && persp->ContainsView(part.Cast ()); } return false; } bool WorkbenchPage::Close() { bool ret; //BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { ret = window->ClosePage(IWorkbenchPage::Pointer(this), true); // } // }); return ret; } bool WorkbenchPage::CloseAllSavedEditors() { // get the Saved editors QList editors = this->GetEditorReferences(); QList savedEditors; for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { IEditorReference::Pointer editor = *iter; if (!editor->IsDirty()) { savedEditors.push_back(editor); } } //there are no unsaved editors if (savedEditors.empty()) { return true; } return this->CloseEditors(savedEditors, false); } bool WorkbenchPage::CloseAllEditors(bool save) { return this->CloseEditors(this->GetEditorReferences(), save); } void WorkbenchPage::UpdateActivePart() { if (this->IsDeferred()) { return; } IWorkbenchPartReference::Pointer oldActivePart = partList->GetActivePartReference(); IWorkbenchPartReference::Pointer oldActiveEditor = partList->GetActiveEditorReference(); IWorkbenchPartReference::Pointer newActivePart; IEditorReference::Pointer newActiveEditor; if (!window->IsClosing()) { // If an editor is active, try to keep an editor active if (oldActiveEditor && oldActivePart == oldActiveEditor) { newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); newActivePart = newActiveEditor; if (newActivePart == 0) { // Only activate a non-editor if there's no editors left newActivePart = activationList->GetActiveReference(false); } } else { // If a non-editor is active, activate whatever was activated most recently newActivePart = activationList->GetActiveReference(false); if (newActivePart.Cast () != 0) { // If that happens to be an editor, make it the active editor as well newActiveEditor = newActivePart.Cast (); } else { // Otherwise, select whatever editor was most recently active newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); } } } if (oldActiveEditor != newActiveEditor) { this->MakeActiveEditor(newActiveEditor); } if (newActivePart != oldActivePart) { this->MakeActive(newActivePart); } } void WorkbenchPage::MakeActive(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { IWorkbenchPart::Pointer newActive = ref->GetPart(true); if (newActive == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { this->Activate(newActive); } } } void WorkbenchPage::MakeActiveEditor(IEditorReference::Pointer ref) { if (ref == this->GetActiveEditorReference()) { return; } IEditorPart::Pointer part = (ref == 0) ? IEditorPart::Pointer(0) : ref->GetEditor(true); if (part) { editorMgr->SetVisibleEditor(ref, false); //navigationHistory.MarkEditor(part); } actionSwitcher.UpdateTopEditor(part); if (ref) { activationList->BringToTop(this->GetReference(part)); } partList->SetActiveEditor(ref); } bool WorkbenchPage::CloseEditors( const QList& refArray, bool save) { if (refArray.empty()) { return true; } IWorkbenchPage::Pointer thisPage(this); // Check if we're being asked to close any parts that are already closed or cannot // be closed at this time QList editorRefs; for (QList::const_iterator iter = refArray.begin(); iter != refArray.end(); ++iter) { IEditorReference::Pointer reference = *iter; // If we're in the middle of creating this part, this is a programming error. Abort the entire // close operation. This usually occurs if someone tries to open a dialog in a method that // isn't allowed to do so, and a *syncExec tries to close the part. If this shows up in a log // file with a dialog's event loop on the stack, then the code that opened the dialog is usually // at fault. if (partBeingActivated == reference) { ctkRuntimeException re( "WARNING: Blocked recursive attempt to close part " + partBeingActivated->GetId() + " while still in the middle of activating it"); WorkbenchPlugin::Log(re); return false; } // if (reference.Cast () != 0) // { // WorkbenchPartReference::Pointer ref = reference.Cast(); // // // If we're being asked to close a part that is disposed (ie: already closed), // // skip it and proceed with closing the remaining parts. // if (ref.isDisposed()) // { // continue; // } // } editorRefs.push_back(reference); } // notify the model manager before the close QList partsToClose; for (int i = 0; i < editorRefs.size(); i++) { IWorkbenchPart::Pointer refPart = editorRefs[i]->GetPart(false); if (refPart != 0) { partsToClose.push_back(refPart); } } SaveablesList::Pointer modelManager; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (partsToClose.size() > 0) { modelManager = dynamic_cast( this->GetWorkbenchWindow()->GetService()); // this may prompt for saving and return 0 if the user canceled: postCloseInfo = modelManager->PreCloseParts(partsToClose, save, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { return false; } } // Fire pre-removal changes for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Notify interested listeners before the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_CLOSE); } this->DeferUpdates(true); try { if (modelManager != 0) { modelManager->PostClose(postCloseInfo); } // Close all editors. for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Remove editor from the presentation editorPresentation->CloseEditor(ref); this->PartRemoved(ref.Cast ()); } } catch (...) { } this->DeferUpdates(false); // Notify interested listeners after the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_CLOSE); // Return true on success. return true; } void WorkbenchPage::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferring(); } deferCount++; } else { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } void WorkbenchPage::StartDeferring() { //editorPresentation.getLayoutPart().deferUpdates(true); } void WorkbenchPage::HandleDeferredEvents() { editorPresentation->GetLayoutPart()->DeferUpdates(false); this->UpdateActivePart(); QList disposals = pendingDisposals; pendingDisposals.clear(); for (int i = 0; i < disposals.size(); i++) { this->DisposePart(disposals[i]); } } bool WorkbenchPage::IsDeferred() { return deferCount > 0; } bool WorkbenchPage::CloseEditor(IEditorReference::Pointer editorRef, bool save) { QList list; list.push_back(editorRef); return this->CloseEditors(list, save); } bool WorkbenchPage::CloseEditor(IEditorPart::Pointer editor, bool save) { IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast ().IsNotNull()) { QList list; list.push_back(ref.Cast ()); return this->CloseEditors(list, save); } return false; } void WorkbenchPage::CloseCurrentPerspective(bool saveParts, bool closePage) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) { Perspective::Pointer persp = this->FindPerspective(desc); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(Perspective::Pointer persp, bool saveParts, bool closePage) { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } QList partsToSave; QList viewsToClose; // collect views that will go away and views that are dirty QList viewReferences = persp->GetViewReferences(); for (int i = 0; i < viewReferences.size(); i++) { IViewReference::Pointer reference = viewReferences[i]; if (this->GetViewFactory()->GetReferenceCount(reference) == 1) { IViewPart::Pointer viewPart = reference->GetView(false); if (viewPart != 0) { viewsToClose.push_back(viewPart); if (saveParts && reference->IsDirty()) { partsToSave.push_back(viewPart); } } } } if (saveParts && perspList.Size() == 1) { // collect editors that are dirty QList editorReferences = this->GetEditorReferences(); for (QList::iterator refIter = editorReferences.begin(); refIter != editorReferences.end(); ++refIter) { IEditorReference::Pointer reference = *refIter; if (reference->IsDirty()) { IEditorPart::Pointer editorPart = reference->GetEditor(false); if (editorPart != 0) { partsToSave.push_back(editorPart); } } } } if (saveParts && !partsToSave.empty()) { if (!EditorManager::SaveAll(partsToSave, true, true, false, IWorkbenchWindow::Pointer(window))) { // user canceled return; } } // Close all editors on last perspective close if (perspList.Size() == 1 && this->GetEditorManager()->GetEditorCount() > 0) { // Close all editors if (!this->CloseAllEditors(false)) { return; } } // closeAllEditors already notified the saveables list about the editors. SaveablesList::Pointer saveablesList( dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); // we took care of the saving already, so pass in false (postCloseInfo will be non-0) SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(viewsToClose, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); // Dispose of the perspective bool isActive = (perspList.GetActive() == persp); if (isActive) { this->SetPerspective(perspList.GetNextActive()); } this->DisposePerspective(persp, true); if (closePage && perspList.Size() == 0) { this->Close(); } } void WorkbenchPage::CloseAllPerspectives(bool saveEditors, bool closePage) { if (perspList.IsEmpty()) { return; } // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } if (saveEditors) { if (!this->SaveAllEditors(true)) { return; } } // Close all editors if (!this->CloseAllEditors(false)) { return; } // Deactivate the active perspective and part this->SetPerspective(Perspective::Pointer(0)); // Close each perspective in turn PerspectiveList oldList = perspList; perspList = PerspectiveList(); for (PerspectiveList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { this->ClosePerspective(*itr, false, false); } if (closePage) { this->Close(); } } void WorkbenchPage::CreateClientComposite() { void* parent = window->GetPageComposite(); // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() // { composite = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateClientComposite( parent); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); // Make visible on activate. // force the client composite to be layed out // parent.layout(); // } // }); } Perspective::Pointer WorkbenchPage::CreatePerspective( PerspectiveDescriptor::Pointer desc, bool notify) { QString label = desc->GetId(); // debugging only try { //UIStats.start(UIStats.CREATE_PERSPECTIVE, label); WorkbenchPage::Pointer thisPage(this); Perspective::Pointer persp(new Perspective(desc, thisPage)); perspList.Add(persp); if (notify) { window->FirePerspectiveOpened(thisPage, desc); } //if the perspective is fresh and uncustomzied then it is not dirty //no reset will be prompted for if (!desc->HasCustomDefinition()) { dirtyPerspectives.erase(desc->GetId()); } return persp; } catch (WorkbenchException& /*e*/) { if (!window->GetWorkbenchImpl()->IsStarting()) { MessageDialog::OpenError(window->GetShell(), "Error", "Problems opening perspective \"" + desc->GetId() + "\""); } return Perspective::Pointer(0); } // finally // { // UIStats.end(UIStats.CREATE_PERSPECTIVE, desc.getId(), label); // } } void WorkbenchPage::PartAdded(WorkbenchPartReference::Pointer ref) { activationList->Add(ref); partList->AddPart(ref); this->UpdateActivePart(); } void WorkbenchPage::PartRemoved(WorkbenchPartReference::Pointer ref) { activationList->Remove(ref); this->DisposePart(ref); } void WorkbenchPage::DisposePart(WorkbenchPartReference::Pointer ref) { if (this->IsDeferred()) { pendingDisposals.push_back(ref); } else { partList->RemovePart(ref); ref->Dispose(); } } void WorkbenchPage::DeactivatePart(IWorkbenchPart::Pointer part) { if (part.IsNotNull()) { PartSite::Pointer site = part->GetSite().Cast (); site->GetPane()->ShowFocus(false); } } void WorkbenchPage::DetachView(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } PerspectiveHelper* presentation = persp->GetPresentation(); presentation->DetachPart(ref); } void WorkbenchPage::AttachView(IViewReference::Pointer ref) { PerspectiveHelper* presentation = this->GetPerspectivePresentation(); presentation->AttachPart(ref); } WorkbenchPage::~WorkbenchPage() { // increment reference count to prevent recursive deletes this->Register(); { { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); // Close and dispose the editors. this->CloseAllEditors(false); // Need to make sure model data is cleaned up when the page is // disposed. Collect all the views on the page and notify the // saveable list of a pre/post close. This will free model data. QList partsToClose = this->GetOpenParts(); QList dirtyParts; for (int i = 0; i < partsToClose.size(); i++) { IWorkbenchPart::Pointer part = partsToClose[i]->GetPart(false); if (part != 0 && part.Cast () != 0) { dirtyParts.push_back(part); } } SaveablesList::Pointer saveablesList(dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(dirtyParts, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); IWorkbenchPage::Pointer thisPage(this); // Get rid of perspectives. This will close the views for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer perspective = *itr; window->FirePerspectiveClosed(thisPage, perspective->GetDesc()); //perspective->Dispose(); } perspList = PerspectiveList(); // Get rid of editor presentation. //editorPresentation->Dispose(); // Get rid of composite. //composite.dispose(); //navigationHistory.dispose(); //stickyViewMan.clear(); // if (tracker != 0) // { // tracker.close(); // } // // if we're destroying a window in a non-shutdown situation then we should // // clean up the working set we made. // if (!window->GetWorkbench()->IsClosing()) // { // if (aggregateWorkingSet != 0) // { // PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet( // aggregateWorkingSet); // } // } } partBeingActivated = 0; pendingDisposals.clear(); stickyViewMan = 0; delete viewFactory; delete editorPresentation; delete editorMgr; delete activationList; deferredActivePersp = 0; dirtyPerspectives.clear(); delete selectionService; partList.reset(); } // decrement reference count again, without explicit deletion this->UnRegister(false); } void WorkbenchPage::DisposePerspective(Perspective::Pointer persp, bool notify) { // Get rid of perspective. perspList.Remove(persp); if (notify) { IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveClosed(thisPage, persp->GetDesc()); } //persp->Dispose(); stickyViewMan->Remove(persp->GetDesc()->GetId()); } Perspective::Pointer WorkbenchPage::FindPerspective( IPerspectiveDescriptor::Pointer desc) { for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer mgr = *itr; if (desc->GetId() == mgr->GetDesc()->GetId()) { return mgr; } } return Perspective::Pointer(0); } IViewPart::Pointer WorkbenchPage::FindView(const QString& id) { IViewReference::Pointer ref = this->FindViewReference(id); if (ref == 0) { return IViewPart::Pointer(0); } return ref->GetView(true); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId) { return this->FindViewReference(viewId, ""); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId, const QString& secondaryId) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewReference::Pointer(0); } return persp->FindView(viewId, secondaryId); } IEditorPart::Pointer WorkbenchPage::GetActiveEditor() { return partList->GetActiveEditor(); } IEditorReference::Pointer WorkbenchPage::GetActiveEditorReference() { return partList->GetActiveEditorReference(); } IWorkbenchPart::Pointer WorkbenchPage::GetActivePart() { return partList->GetActivePart(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetActivePartReference() { return partList->GetActivePartReference(); } Perspective::Pointer WorkbenchPage::GetActivePerspective() { return perspList.GetActive(); } void* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } -bool WorkbenchPage::HasView(const std::string& perspectiveId, const std::string& viewId) +bool WorkbenchPage::HasView(const QString& perspectiveId, const QString& viewId) { - PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives(); - for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++) + PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives(); + for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++) + { + SmartPointer p = *it; + if (p->GetDesc()->GetId() == perspectiveId) { - SmartPointer p = *it; - if ( p->GetDesc()->GetId()==perspectiveId) - { - if (p->ContainsView(viewId) ) - { - return true; - } - } + if (p->ContainsView(viewId)) + { + return true; + } } - return false; + } + return false; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } QList WorkbenchPage::GetEditors() { QList refs = this->GetEditorReferences(); QList result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (QList::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } QList WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } QList WorkbenchPage::GetDirtyParts() { QList result; QList allParts = this->GetAllParts(); for (int i = 0; i < allParts.size(); i++) { IWorkbenchPartReference::Pointer reference = allParts[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0 && part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty()) { result.push_back(saveable); } } } return result; } IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input) { return this->GetEditorManager()->FindEditor(input); } QList WorkbenchPage::FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } QList WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } QString WorkbenchPage::GetLabel() { QString label = ""; // IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input, // IWorkbenchAdapter.class); // if (adapter != 0) // { // label = adapter.getLabel(input); // } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { label = label + " - " + persp->GetDesc()->GetLabel(); } else if (deferredActivePersp != 0) { label = label + " - " + deferredActivePersp->GetLabel(); } return label; } IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective() { if (deferredActivePersp != 0) { return deferredActivePersp; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetDesc(); } else { return IPerspectiveDescriptor::Pointer(0); } } ISelection::ConstPointer WorkbenchPage::GetSelection() const { return selectionService->GetSelection(); } ISelection::ConstPointer WorkbenchPage::GetSelection(const QString& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const QString& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } QList WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return QList(); } } QList WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } QList WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } QList parts; if (persp != 0) { QList refs = persp->GetViewReferences(); for (int i = 0; i < refs.size(); i++) { IViewPart::Pointer part = refs[i]->GetPart(restore).Cast (); if (part != 0) { parts.push_back(part); } } } return parts; } IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() { return IWorkbenchWindow::Pointer(window); } void WorkbenchPage::HideView(IViewReference::Pointer ref) { // Sanity check. if (ref == 0) { return; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } bool promptedForSave = false; IViewPart::Pointer view = ref->GetView(false); if (view != 0) { if (!this->CertifyPart(view)) { return; } // Confirm. if (view.Cast () != 0) { ISaveablePart::Pointer saveable = view.Cast (); if (saveable->IsSaveOnCloseNeeded()) { IWorkbenchWindow::Pointer window = view->GetSite()->GetWorkbenchWindow(); QList partsToSave; partsToSave.push_back(view); bool success = EditorManager::SaveAll(partsToSave, true, true, false, window); if (!success) { // the user cancelled. return; } promptedForSave = true; } } } int refCount = this->GetViewFactory()->GetReferenceCount(ref); SaveablesList* saveablesList = NULL; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = dynamic_cast( actualPart->GetSite()->GetService()); QList partsToClose; partsToClose.push_back(actualPart); postCloseInfo = saveablesList->PreCloseParts(partsToClose, !promptedForSave, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { // cancel return; } } } IWorkbenchPage::Pointer thisPage(this); // Notify interested listeners before the hide window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref, CHANGE_VIEW_HIDE); PartPane::Pointer pane = this->GetPane(ref.Cast ()); pane->SetInLayout(false); this->UpdateActivePart(); if (saveablesList != 0) { saveablesList->PostClose(postCloseInfo); } // Hide the part. persp->HideView(ref); // Notify interested listeners after the hide window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_VIEW_HIDE); } void WorkbenchPage::RefreshActiveView() { this->UpdateActivePart(); } void WorkbenchPage::HideView(IViewPart::Pointer view) { this->HideView(this->GetReference(view).Cast ()); } void WorkbenchPage::Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras) { // Save args. this->window = w; this->input = input; this->composite = 0; this->viewFactory = 0; this->activationList = new ActivationList(this); this->selectionService = new PageSelectionService(this); this->partList.reset(new WorkbenchPagePartList(this->selectionService)); this->stickyViewMan = new StickyViewManager(this); //actionSets = new ActionSetManager(w); deferCount = 0; // Create presentation. this->CreateClientComposite(); editorPresentation = new EditorAreaHelper(this); editorMgr = new EditorManager(WorkbenchWindow::Pointer(window), WorkbenchPage::Pointer(this), editorPresentation); //TODO WorkbenchPage perspective reorder listener? // // add this page as a client to be notified when the UI has re-ordered perspectives // // so that the order can be properly maintained in the receiver. // // E.g. a UI might support drag-and-drop and will need to make this known to ensure // // #saveState and #restoreState do not lose this re-ordering // w.addPerspectiveReorderListener(new IReorderListener() // { // public void WorkbenchPage::reorder(Object perspective, int newLoc) // { // perspList.reorder((IPerspectiveDescriptor)perspective, newLoc); // } // }); if (openExtras) { this->OpenPerspectiveExtras(); } // Get perspective descriptor. if (layoutID != "") { PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( layoutID).Cast (); if (desc == 0) { throw WorkbenchException("Unable to create Perspective " + layoutID + ". There is no corresponding perspective extension."); } Perspective::Pointer persp = this->FindPerspective(desc); if (persp == 0) { persp = this->CreatePerspective(desc, true); } perspList.SetActive(persp); window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc); } // getExtensionTracker() .registerHandler(perspectiveChangeHandler, // ExtensionTracker .createExtensionPointFilter( // getPerspectiveExtensionPoint())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras QString extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); QList descs; foreach (QString id, extras.split(", ", QString::SkipEmptyParts)) { if (id.trimmed().isEmpty()) continue; IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(id); if (desc != 0) { descs.push_back(desc); } } // HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list. // So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared. for (int i = (int) descs.size(); --i >= 0;) { PerspectiveDescriptor::Pointer desc = descs[i].Cast (); if (this->FindPerspective(desc) == 0) { this->CreatePerspective(desc, true); } } } bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); return pane != 0 && pane->GetVisible(); } bool WorkbenchPage::IsEditorAreaVisible() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return false; } return persp->IsEditorAreaVisible(); } bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { //return persp->IsFastView(ref); return false; } else { return false; } } bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsCloseable(ref); } return false; } bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsMoveable(ref); } return false; } bool WorkbenchPage::IsFixedLayout() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsFixedLayout(); } else { return false; } } bool WorkbenchPage::IsSaveNeeded() { return this->GetEditorManager()->IsSaveAllNeeded(); } void WorkbenchPage::OnActivate() { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true); Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->OnActivate(); this->UpdateVisibility(Perspective::Pointer(0), persp); } } void WorkbenchPage::OnDeactivate() { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); if (this->GetActivePerspective() != 0) { this->GetActivePerspective()->OnDeactivate(); } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); } void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) { // Rather than calling editor.setInput on the editor directly, we do it through the part reference. // This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response // to the input change... but if all editors obeyed their API contract, the "else" branch would be // sufficient. IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast () != 0) { EditorReference::Pointer editorRef = ref.Cast (); editorRef->SetInput(input); } else { editor->SetInput(input); } //navigationHistory.markEditor(editor); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { if (input == 0 || editorID == "") { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditor(input, editorID, activate, matchFlags, editorState); } IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor( IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { if (input == 0 || !(editorDescriptor.Cast () != 0)) { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast< EditorDescriptor> (), activate, editorState); // } // }); } IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor, activate, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched( IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { // If an editor already exists for the input, use it. IEditorPart::Pointer editor; // Reuse an existing open editor, unless we are in "new editor tab management" mode editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags); if (editor != 0) { if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID) { if (editor->IsDirty()) { QList dlgLabels; dlgLabels.push_back("Yes"); dlgLabels.push_back("No"); dlgLabels.push_back("Cancel"); IDialog::Pointer dialog = MessageDialog::CreateMessageDialog( this->GetWorkbenchWindow()->GetShell(), "Save", (void*) 0, // accept the default window icon "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", IDialog::QUESTION, dlgLabels, 0); int saveFile = dialog->Open(); if (saveFile == 0) { // try // { IEditorPart::Pointer editorToSave = editor; // getWorkbenchWindow().run(false, false, // new IRunnableWithProgress() // { // public void WorkbenchPage::run(IProgressMonitor monitor) // throws InvocationTargetException, // InterruptedException // { //TODO progress monitor editorToSave->DoSave();//monitor); // } // }); // } // catch (InvocationTargetException& e) // { // throw(RuntimeException) e->GetTargetException(); // } // catch (InterruptedException& e) // { // return 0; // } } else if (saveFile == 2) { return IEditorPart::Pointer(0); } } } else { // // do the IShowEditorInput notification before showing the editor // // to reduce flicker // if (editor.Cast () != 0) // { // ((IShowEditorInput) editor).showEditorInput(input); // } this->ShowEditor(activate, editor); return editor; } } // Otherwise, create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor( editorID, input, true, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { IEditorPart::Pointer editor; // Create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor, input, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } void WorkbenchPage::OpenEmptyTab() { IEditorPart::Pointer editor; EditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEmptyTab().Cast (); if (ref != 0) { editor = ref->GetEmptyEditor( dynamic_cast (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor( EditorRegistry::EMPTY_EDITOR_ID).Cast ()); } if (editor != 0) { this->SetEditorAreaVisible(true); this->Activate(editor); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } } void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor) { this->SetEditorAreaVisible(true); if (activate) { //zoomOutIfNecessary(editor); this->Activate(editor); } else { this->BringToTop(editor); } } bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor) { WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast< WorkbenchPartReference> (); return ref != 0 && ref->IsPinned(); } /** * Removes an IPartListener from the part service. */ void WorkbenchPage::RemovePartListener(IPartListener* l) { partList->GetPartService()->RemovePartListener(l); } /** * Implements IWorkbenchPage * * @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener) * @since 2.0 * @deprecated individual views should store a working set if needed and * register a property change listener directly with the * working set manager to receive notification when the view * working set is removed. */ // void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) { // propertyChangeListeners.remove(listener); // } void WorkbenchPage::RemoveSelectionListener(ISelectionListener* listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener(ISelectionListener* listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemovePostSelectionListener(partId, listener); } void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } // Real work. this->SetActivePart(part); } /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ void WorkbenchPage::ResetPerspective() { // Run op in busy cursor. // Use set redraw to eliminate the "flash" that can occur in the // coolbar as the perspective is reset. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // try // { // mgr.getControl2().setRedraw(false); // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusyResetPerspective(); // } // }); // }finally // { // mgr.getControl2().setRedraw(true); // } } bool WorkbenchPage::RestoreState(IMemento::Pointer memento, const IPerspectiveDescriptor::Pointer activeDescriptor) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { this->DeferUpdates(true); // }}); try { // Restore working set QString pageName; memento->GetString(WorkbenchConstants::TAG_LABEL, pageName); // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH)) // { // label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$ // } try { //UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$ // MultiStatus result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToRestorePerspective, // pageName), 0); bool result = true; // String workingSetName = memento .getString( // IWorkbenchConstants.TAG_WORKING_SET); // if (workingSetName != 0) // { // AbstractWorkingSetManager // workingSetManager = // (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager(); // setWorkingSet(workingSetManager.getWorkingSet(workingSetName)); // } // // IMemento workingSetMem = memento .getChild( // IWorkbenchConstants.TAG_WORKING_SETS); // if (workingSetMem != 0) // { // QList workingSetChildren = // workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET); // List workingSetList = new ArrayList(workingSetChildren.length); // for (int i = 0; i < workingSetChildren.length; i++) // { // IWorkingSet // set = // getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet( // workingSetChildren[i].getID()); // if (set != 0) // { // workingSetList.add(set); // } // } // // workingSets = (IWorkingSet[]) workingSetList .toArray( // new IWorkingSet[workingSetList.size()]); // } // // aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID); // // IWorkingSet setWithId = // window.getWorkbench().getWorkingSetManager().getWorkingSet( // aggregateWorkingSetId); // // // check to see if the set has already been made and assign it if it has // if (setWithId.Cast () != 0) // { // aggregateWorkingSet = (AggregateWorkingSet) setWithId; // } // Restore editor manager. IMemento::Pointer childMem = memento->GetChild( WorkbenchConstants::TAG_EDITORS); //result.merge(getEditorManager().restoreState(childMem)); result &= this->GetEditorManager()->RestoreState(childMem); childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS); if (childMem) { //result.merge(getViewFactory().restoreState(childMem)); result &= this->GetViewFactory()->RestoreState(childMem); } // Get persp block. childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES); QString activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); QString activePartSecondaryID; if (!activePartID.isEmpty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.isEmpty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } QString activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. QList perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; IPerspectiveDescriptor::Pointer validPersp; for (int i = 0; i < perspMems.size(); i++) { IMemento::Pointer current = perspMems[i]; // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { Perspective::Pointer persp(new Perspective( PerspectiveDescriptor::Pointer(0), WorkbenchPage::Pointer(this))); //result.merge(persp.restoreState(current)); result &= persp->RestoreState(current); IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc.IsNotNull()) { validPersp=desc; } else { IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->CreatePerspective("Hallo",validPersp); } if (desc == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); //berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry()->Add window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc); // } // }); } bool restoreActivePerspective = false; if (!activeDescriptor) { restoreActivePerspective = true; } else if (activePerspective && activePerspective->GetDesc() == activeDescriptor) { restoreActivePerspective = true; } else { restoreActivePerspective = false; activePerspective = this->CreatePerspective(activeDescriptor.Cast< PerspectiveDescriptor> (), true); if (activePerspective == 0) { // result .merge( // new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.Workbench_showPerspectiveError, // activeDescriptor.getId()), 0)); result &= false; } } perspList.SetActive(activePerspective); // Make sure we have a valid perspective to work with, // otherwise return. activePerspective = perspList.GetActive(); if (activePerspective == 0) { activePerspective = perspList.GetNextActive(); perspList.SetActive(activePerspective); } if (activePerspective && restoreActivePerspective) { //result.merge(activePerspective.restoreState()); result &= activePerspective->RestoreState(); } if (activePerspective) { Perspective::Pointer myPerspective = activePerspective; QString myActivePartId = activePartID; QString mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.isEmpty()) { IWorkbenchPartReference::Pointer ref = myPerspective->FindView( myActivePartId, mySecondaryId); if (ref) { activationList->SetActive(ref); } } // }}); } // childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY); // if (childMem) // { // navigationHistory.restoreState(childMem); // } // else if (GetActiveEditor()) // { // navigationHistory.markEditor(getActiveEditor()); // } // // restore sticky view state stickyViewMan->Restore(memento); // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); return result; } catch (...) { // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ throw ; } } catch (...) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); throw; } } bool WorkbenchPage::SaveAllEditors(bool confirm) { return this->SaveAllEditors(confirm, false); } bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources) { return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources); } bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm) { // Do not certify part do allow editors inside a multipageeditor to // call this. return this->GetEditorManager()->SavePart(saveable, part, confirm); } bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm) { return this->SavePart(editor, editor, confirm); } /** * Saves the current perspective. */ void WorkbenchPage::SavePerspective() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDesc(); } /** * Saves the perspective. */ void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc(); // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDescAs(newDesc); window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc); } /** * Save the state of the page. */ bool WorkbenchPage::SaveState(IMemento::Pointer memento) { // // We must unzoom to get correct layout. // if (isZoomed()) // { // zoomOut(); // } // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToSavePerspective, // getLabel()), 0); bool result = true; // Save editor manager. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS); //result.merge(editorMgr.saveState(childMem)); result &= editorMgr->SaveState(childMem); childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS); //result.merge(getViewFactory().saveState(childMem)); result &= this->GetViewFactory()->SaveState(childMem); // Create persp block. childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES); if (this->GetPerspective()) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, this->GetPerspective()->GetId()); } if (this->GetActivePart() != 0) { if (this->GetActivePart().Cast ()) { IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast(); if (ref) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, ViewFactory::GetKey(ref)); } } else { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, this->GetActivePart()->GetSite()->GetId()); } } // Save each perspective in opened order for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { IMemento::Pointer gChildMem = childMem->CreateChild( WorkbenchConstants::TAG_PERSPECTIVE); //result.merge(persp.saveState(gChildMem)); result &= (*itr)->SaveState(gChildMem); } // // Save working set if set // if (workingSet != 0) // { // memento.putString(IWorkbenchConstants.TAG_WORKING_SET, // workingSet .getName()); // } // // IMemento workingSetMem = memento .createChild( // IWorkbenchConstants.TAG_WORKING_SETS); // for (int i = 0; i < workingSets.length; i++) // { // workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET, // workingSets[i].getName()); // } // // if (aggregateWorkingSetId != 0) // { // memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId); // } // // navigationHistory.saveState(memento .createChild( // IWorkbenchConstants.TAG_NAVIGATION_HISTORY)); // // save the sticky activation state stickyViewMan->Save(memento); return result; } QString WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } QString WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { return "0"; //$NON-NLS-1$ } return ref->GetId(); } void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize it. if (this->GetActivePart() == newPart) { return; } if (partBeingActivated != 0) { if (partBeingActivated->GetPart(false) != newPart) { WorkbenchPlugin::Log(ctkRuntimeException( QString("WARNING: Prevented recursive attempt to activate part ") + this->GetId(newPart) + " while still in the middle of activating part " + this->GetId( partBeingActivated))); } return; } //No need to change the history if the active editor is becoming the // active part // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.ACTIVATE_PART)) // { // label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$ // } try { IWorkbenchPartReference::Pointer partref = this->GetReference(newPart); IWorkbenchPartReference::Pointer realPartRef; if (newPart != 0) { IWorkbenchPartSite::Pointer site = newPart->GetSite(); if (site.Cast () != 0) { realPartRef = site.Cast ()->GetPane()->GetPartReference(); } } partBeingActivated = realPartRef; //UIStats.start(UIStats.ACTIVATE_PART, label); // Notify perspective. It may deactivate fast view. Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->PartActivated(newPart); } // Deactivate old part IWorkbenchPart::Pointer oldPart = this->GetActivePart(); if (oldPart != 0) { this->DeactivatePart(oldPart); } // Set active part. if (newPart != 0) { activationList->SetActive(newPart); if (newPart.Cast () != 0) { this->MakeActiveEditor(realPartRef.Cast ()); } } this->ActivatePart(newPart); actionSwitcher.UpdateActivePart(newPart); partList->SetActivePart(partref); } catch (std::exception& e) { partBeingActivated = 0; // Object blame = newPart == 0 ? (Object) this : newPart; // UIStats.end(UIStats.ACTIVATE_PART, blame, label); throw e; } partBeingActivated = 0; } void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } if (showEditorArea == persp->IsEditorAreaVisible()) { return; } // // If parts change always update zoom. // if (isZoomed()) // { // zoomOut(); // } // Update editor area visibility. IWorkbenchPage::Pointer thisPage(this); if (showEditorArea) { persp->ShowEditorArea(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_SHOW); } else { persp->HideEditorArea(); this->UpdateActivePart(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_HIDE); } } /** * Sets the layout of the page. Assumes the new perspective is not 0. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp) { // Don't do anything if already active layout Perspective::Pointer oldPersp = this->GetActivePerspective(); if (oldPersp == newPersp) { return; } window->LargeUpdateStart(); std::exception exc; bool exceptionOccured = false; try { IWorkbenchPage::Pointer thisPage(this); if (oldPersp != 0) { // fire the pre-deactivate window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc()); } if (newPersp != 0) { bool status = newPersp->RestoreState(); if (!status) { QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; MessageDialog::OpenError(this->GetWorkbenchWindow()->GetShell(), title, msg); } } // Deactivate the old layout if (oldPersp != 0) { oldPersp->OnDeactivate(); // Notify listeners of deactivation window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc()); } // Activate the new layout perspList.SetActive(newPersp); if (newPersp != 0) { newPersp->OnActivate(); // Notify listeners of activation window->FirePerspectiveActivated(thisPage, newPersp->GetDesc()); } this->UpdateVisibility(oldPersp, newPersp); // Update the window //TODO action sets //window->UpdateActionSets(); // Update sticky views stickyViewMan->Update(oldPersp, newPersp); } catch (std::exception& e) { exc = e; exceptionOccured = true; } window->LargeUpdateEnd(); if (newPersp == 0) { return; } IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc(); if (desc == 0) { return; } if (dirtyPerspectives.erase(desc->GetId())) { this->SuggestReset(); } if (exceptionOccured) throw exc; } void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp, Perspective::Pointer newPersp) { // Flag all parts in the old perspective QList oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (int i = 0; i < oldRefs.size(); i++) { PartPane::Pointer pane = oldRefs[i].Cast ()->GetPane(); pane->SetInLayout(false); } } PerspectiveHelper* pres = 0; // Make parts in the new perspective visible if (newPersp != 0) { pres = newPersp->GetPresentation(); QList newRefs = newPersp->GetViewReferences(); for (int i = 0; i < newRefs.size(); i++) { WorkbenchPartReference::Pointer ref = newRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres->IsPartVisible(ref)) { activationList->BringToTop(ref); } pane->SetInLayout(true); } } this->UpdateActivePart(); // Hide any parts in the old perspective that are no longer visible for (int i = 0; i < oldRefs.size(); i++) { WorkbenchPartReference::Pointer ref = oldRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres == 0 || !pres->IsPartVisible(ref)) { pane->SetVisible(false); } } } /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc) { if (this->GetPerspective() == desc) { return; } // // Going from multiple to single rows can make the coolbar // // and its adjacent views appear jumpy as perspectives are // // switched. Turn off redraw to help with this. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); std::exception exc; bool exceptionOccured = false; try { //mgr.getControl2().setRedraw(false); //getClientComposite().setRedraw(false); // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusySetPerspective(desc); // } // }); } catch (std::exception& e) { exc = e; exceptionOccured = true; } // getClientComposite().setRedraw(true); // mgr.getControl2().setRedraw(true); IWorkbenchPart::Pointer part = this->GetActivePart(); if (part != 0) { part->SetFocus(); } if (exceptionOccured) throw exc; } PartService* WorkbenchPage::GetPartService() { return dynamic_cast (partList->GetPartService()); } void WorkbenchPage::ResetToolBarLayout() { // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // mgr.resetItemOrder(); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID, const QString& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.indexOf(ViewFactory::ID_SEP) != -1) { throw ctkInvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw ctkInvalidArgumentException("Illegal view mode"); } // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { // try // { return this->BusyShowView(viewID, secondaryID, mode); // } catch (PartInitException& e) // { // result = e; // } // } // }); } bool WorkbenchPage::CertifyMode(int mode) { if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE) return true; return false; } QList WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } QList WorkbenchPage::GetOpenPerspectives() { QList opened = perspList.GetOpenedPerspectives(); QList result; for (QList::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { QListIterator iter(perspList.GetSortedPerspectives()); iter.toBack(); while(iter.hasPrevious()) { Perspective::Pointer p = iter.previous(); if (p->ContainsView(part)) { return p; } }; // we should never get here return Perspective::Pointer(0); } QList WorkbenchPage::GetSortedPerspectives() { QList sortedArray = perspList.GetSortedPerspectives(); QList result; for (QList::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetSortedParts() { //return partList->GetParts(this->GetViewReferences()); return activationList->GetParts(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetReference( IWorkbenchPart::Pointer part) { if (part == 0) { return IWorkbenchPartReference::Pointer(0); } IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } PartSite::Pointer partSite = site.Cast (); PartPane::Pointer pane = partSite->GetPane(); return partSite->GetPartReference(); } // for dynamic UI void WorkbenchPage::AddPerspective(Perspective::Pointer persp) { perspList.Add(persp); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveOpened(thisPage, persp->GetDesc()); } QList WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return QList(); } ILayoutContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); QList list; ILayoutContainer::ChildrenType children = folder->GetChildren(); for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer stackablePart = *childIter; if (stackablePart.Cast () != 0) { IViewReference::Pointer view = stackablePart.Cast ()->GetPartReference().Cast< IViewReference> (); if (view != 0) { list.push_back(view); } } } // sort the list by activation order (most recently activated first) std::sort(list.begin(), list.end(), ActivationOrderPred(activationList)); return list; } QList result; result.push_back(this->GetReference(part).Cast ()); return result; } QList WorkbenchPage::GetViewStack( IViewPart::Pointer part) { QList refStack = this->GetViewReferenceStack( part); QList result; for (int i = 0; i < refStack.size(); i++) { IViewPart::Pointer next = refStack[i]->GetView(false); if (next != 0) { result.push_back(next); } } return result; } void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height) { SashInfo sashInfo; PartPane::Pointer pane = part->GetSite().Cast ()->GetPane(); ILayoutContainer::Pointer container = pane->GetContainer(); LayoutTree::Pointer tree = this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find( container.Cast ()); // retrieve our layout sashes from the layout tree this->FindSashParts(tree, pane->FindSashes(), sashInfo); // first set the width int deltaWidth = width - pane->GetBounds().width; if (sashInfo.right != 0) { Rectangle rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x) - rightBounds.x) / rightBounds.width); // complete the resize sashInfo.rightNode->SetBounds(rightBounds); } else if (sashInfo.left != 0) { Rectangle leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x - deltaWidth) - leftBounds.x) / leftBounds.width); // complete the resize sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds()); } // next set the height int deltaHeight = height - pane->GetBounds().height; if (sashInfo.bottom != 0) { Rectangle bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y) - bottomBounds.y) / bottomBounds.height); // complete the resize sashInfo.bottomNode->SetBounds(bottomBounds); } else if (sashInfo.top != 0) { Rectangle topBounds = sashInfo.topNode->GetBounds(); // set the ratio sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y - deltaHeight) - topBounds.y) / topBounds.height); // complete the resize sashInfo.topNode->SetBounds(topBounds); } } void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree, const PartPane::Sashes& sashes, SashInfo& info) { LayoutTree::Pointer parent(tree->GetParent()); if (parent == 0) { return; } if (parent->part.Cast () != 0) { // get the layout part sash from this tree node LayoutPartSash::Pointer sash = parent->part.Cast (); // make sure it has a sash control void* control = sash->GetControl(); if (control != 0) { // check for a vertical sash if (sash->IsVertical()) { if (sashes.left == control) { info.left = sash; info.leftNode = parent->FindSash(sash); } else if (sashes.right == control) { info.right = sash; info.rightNode = parent->FindSash(sash); } } // check for a horizontal sash else { if (sashes.top == control) { info.top = sash; info.topNode = parent->FindSash(sash); } else if (sashes.bottom == control) { info.bottom = sash; info.bottomNode = parent->FindSash(sash); } } } } // recursive call to continue up the tree this->FindSashParts(parent, sashes, info); } QList WorkbenchPage::GetAllParts() { QList views = viewFactory->GetViews(); QList editors = this->GetEditorReferences(); QList result; for (int i = 0; i < views.size(); i++) { result.push_back(views[i]); } for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { result.push_back(*iter); } return result; } QList WorkbenchPage::GetOpenParts() { QList refs = this->GetAllParts(); QList result; for (int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0) { result.push_back(reference); } } return result; } void WorkbenchPage::TestInvariants() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->TestInvariants(); // When we have widgets, ensure that there is no situation where the editor area is visible // and the perspective doesn't want an editor area. if (this->GetClientComposite() && editorPresentation->GetLayoutPart()->IsVisible()) { poco_assert(persp->IsEditorAreaVisible()); } } } /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() */ // IExtensionTracker WorkbenchPage::GetExtensionTracker() // { // if (tracker == 0) // { // tracker = new UIExtensionTracker(getWorkbenchWindow().getWorkbench().getDisplay()); // } // return tracker; // } /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ QList WorkbenchPage::GetPerspectiveShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetPerspectiveShortcuts(); } QList WorkbenchPage::GetShowViewShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetShowViewShortcuts(); } void WorkbenchPage::SuggestReset() { IWorkbench* workbench = this->GetWorkbenchWindow()->GetWorkbench(); // workbench.getDisplay().asyncExec(new Runnable() // { // public void WorkbenchPage::run() // { Shell::Pointer parentShell; IWorkbenchWindow::Pointer window = workbench->GetActiveWorkbenchWindow(); if (window == 0) { if (workbench->GetWorkbenchWindowCount() == 0) { return; } window = workbench->GetWorkbenchWindows()[0]; } parentShell = window->GetShell(); if (MessageDialog::OpenQuestion(parentShell, "Reset Perspective?", "Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?")) { IWorkbenchPage::Pointer page = window->GetActivePage(); if (page == 0) { return; } page->ResetPerspective(); } // } // }); } bool WorkbenchPage::IsPartVisible( IWorkbenchPartReference::Pointer reference) { IWorkbenchPart::Pointer part = reference->GetPart(false); // Can't be visible if it isn't created yet if (part == 0) { return false; } return this->IsPartVisible(part); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h index 49acf631b0..9e06de5a48 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h @@ -1,1813 +1,1813 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHPAGE_H_ #define BERRYWORKBENCHPAGE_H_ #include #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPartReference.h" #include "berryIReusableEditor.h" #include "berryILayoutContainer.h" #include "berryIStickyViewManager.h" #include "berryWorkbenchPagePartList.h" #include "berryWorkbenchPartReference.h" #include "berryPageSelectionService.h" #include "berryEditorManager.h" #include "berryViewFactory.h" #include "berryPartPane.h" #include namespace berry { struct IExtensionPoint; //class PartPane; //class PartPane::Sashes; class EditorAreaHelper; class WorkbenchWindow; class Perspective; class PerspectiveHelper; class PerspectiveDescriptor; class LayoutPartSash; class LayoutTree; class LayoutTreeNode; class PartService; /** * \ingroup org_blueberry_ui_internal * * A collection of views and editors in a workbench. */ class BERRY_UI_QT WorkbenchPage: public IWorkbenchPage { public: berryObjectMacro(WorkbenchPage); protected: //TODO Weakpointer WorkbenchWindow* window; friend class ViewFactory; friend class WorkbenchWindow; friend class EditorAreaHelper; friend class WWinPartService; private: /** * Manages editor contributions and action set part associations. */ class ActionSwitcher { private: IWorkbenchPart::WeakPtr activePart; IEditorPart::WeakPtr topEditor; /** * Updates the contributions given the new part as the active part. * * @param newPart * the new active part, may be null */ public: void UpdateActivePart(IWorkbenchPart::Pointer newPart); /** * Updates the contributions given the new part as the topEditor. * * @param newEditor * the new top editor, may be null */ public: void UpdateTopEditor(IEditorPart::Pointer newEditor); /** * Activates the contributions of the given part. If enable * is true the contributions are visible and enabled, * otherwise they are disabled. * * @param part * the part whose contributions are to be activated * @param enable * true the contributions are to be enabled, * not just visible. */ private: void ActivateContributions(IWorkbenchPart::Pointer part, bool enable); /** * Deactivates the contributions of the given part. If remove * is true the contributions are removed, otherwise they * are disabled. * * @param part * the part whose contributions are to be deactivated * @param remove * true the contributions are to be removed, * not just disabled. */ private: void DeactivateContributions(IWorkbenchPart::Pointer part, bool remove); }; class ActivationList { public: //List of parts in the activation order (oldest first) typedef std::deque PartListType; typedef std::deque::iterator PartListIter; typedef std::deque::reverse_iterator PartListReverseIter; private: PartListType parts; WorkbenchPage* page; public: ActivationList(WorkbenchPage* page); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer part); /* * Ensures that the given part appears AFTER any other part in the same * container. */ void BringToTop(SmartPointer ref); /* * Returns the last (most recent) iterator (index) of the given container in the activation list, or returns * end() if the given container does not appear in the activation list. */ PartListIter LastIndexOfContainer(SmartPointer container); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer ref); /* * Add the active part to the beginning of the list. */ void Add(SmartPointer ref); /* * Return the active part. Filter fast views. */ SmartPointer GetActive(); /* * Return the previously active part. Filter fast views. */ SmartPointer GetPreviouslyActive(); SmartPointer GetActiveReference(bool editorsOnly); /* * Retuns the index of the part within the activation list. The higher * the index, the more recently it was used. */ PartListIter IndexOf(SmartPointer part); /* * Returns the index of the part reference within the activation list. * The higher the index, the more recent it was used. */ PartListIter IndexOf(SmartPointer ref); /* * Remove a part from the list */ bool Remove(SmartPointer ref); /* * Returns the topmost editor on the stack, or null if none. */ SmartPointer GetTopEditor(); /* * Returns the editors in activation order (oldest first). */ QList > GetEditors(); /* * Return a list with all parts (editors and views). */ QList > GetParts(); private: SmartPointer GetActive(PartListIter start); SmartPointer GetActiveReference(PartListIter start, bool editorsOnly); /* * Find a part in the list starting from the end and filter * and views from other perspectives. Will filter fast views * unless 'includeActiveFastViews' is true; */ SmartPointer GetActiveReference(PartListIter start, bool editorsOnly, bool skipPartsObscuredByZoom); }; /** * Helper class to keep track of all opened perspective. Both the opened * and used order is kept. */ struct PerspectiveList { public: typedef QList > PerspectiveListType; typedef PerspectiveListType::iterator iterator; private: /** * List of perspectives in the order they were opened; */ PerspectiveListType openedList; /** * List of perspectives in the order they were used. Last element is * the most recently used, and first element is the least recently * used. */ PerspectiveListType usedList; /** * The perspective explicitly set as being the active one */ SmartPointer active; void UpdateActionSets(SmartPointer oldPersp, SmartPointer newPersp); public: /** * Creates an empty instance of the perspective list */ PerspectiveList(); /** * Update the order of the perspectives in the opened list * * @param perspective * @param newLoc */ void Reorder(IPerspectiveDescriptor::Pointer perspective, int newLoc); /** * Return all perspectives in the order they were activated. * * @return an array of perspectives sorted by activation order, least * recently activated perspective last. */ PerspectiveListType GetSortedPerspectives(); /** * Adds a perspective to the list. No check is done for a duplicate when * adding. * @param perspective the perspective to add * @return boolean true if the perspective was added */ bool Add(SmartPointer perspective); /** * Returns an iterator on the perspective list in the order they were * opened. */ PerspectiveListType::iterator Begin(); PerspectiveListType::iterator End(); /** * Returns an array with all opened perspectives */ PerspectiveListType GetOpenedPerspectives(); /** * Removes a perspective from the list. */ bool Remove(SmartPointer perspective); /** * Swap the opened order of old perspective with the new perspective. */ void Swap(SmartPointer oldPerspective, SmartPointer newPerspective); /** * Returns whether the list contains any perspectives */ bool IsEmpty(); /** * Returns the most recently used perspective in the list. */ SmartPointer GetActive(); /** * Returns the next most recently used perspective in the list. */ SmartPointer GetNextActive(); /** * Returns the number of perspectives opened */ PerspectiveListType::size_type Size(); /** * Marks the specified perspective as the most recently used one in the * list. */ void SetActive(SmartPointer perspective); }; IAdaptable* input; void* composite; //Could be delete. This information is in the active part list; ActivationList* activationList; EditorManager* editorMgr; EditorAreaHelper* editorPresentation; //ListenerList propertyChangeListeners = new ListenerList(); PageSelectionService* selectionService; QScopedPointer partList; // = new WorkbenchPagePartList(selectionService); //IActionBars actionBars; ViewFactory* viewFactory; PerspectiveList perspList; SmartPointer deferredActivePersp; //NavigationHistory navigationHistory = new NavigationHistory(this); IStickyViewManager::Pointer stickyViewMan; /** * Returns true if perspective with given id contains view with given id */ - bool HasView(const std::string& perspectiveId, const std::string& viewId); + bool HasView(const QString& perspectiveId, const QString& viewId); /** * If we're in the process of activating a part, this points to the new part. * Otherwise, this is null. */ IWorkbenchPartReference::Pointer partBeingActivated; /** * Contains a list of perspectives that may be dirty due to plugin * installation and removal. */ std::set dirtyPerspectives; ActionSwitcher actionSwitcher; //IExtensionTracker tracker; // Deferral count... delays disposing parts and sending certain events if nonzero int deferCount; // Parts waiting to be disposed QList pendingDisposals; SmartPointer GetPerspectiveExtensionPoint(); public: /** * Constructs a new page with a given perspective and input. * * @param w * the parent window * @param layoutID * must not be null * @param input * the page input * @throws WorkbenchException * on null layout id */ WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input); /** * Constructs a page. restoreState(IMemento) should be * called to restore this page from data stored in a persistance file. * * @param w * the parent window * @param input * the page input * @throws WorkbenchException */ WorkbenchPage(WorkbenchWindow* w, IAdaptable* input); ~WorkbenchPage(); /** * Activates a part. The part will be brought to the front and given focus. * * @param part * the part to activate */ void Activate(IWorkbenchPart::Pointer part); /** * Activates a part. The part is given focus, the pane is hilighted. */ private: void ActivatePart(const IWorkbenchPart::Pointer part); /** * Adds an IPartListener to the part service. */ public: void AddPartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(const QString& partId, ISelectionListener* listener); private: ILayoutContainer::Pointer GetContainer(IWorkbenchPart::Pointer part); private: ILayoutContainer::Pointer GetContainer(IWorkbenchPartReference::Pointer part); private: SmartPointer GetPane(IWorkbenchPart::Pointer part); private: SmartPointer GetPane(IWorkbenchPartReference::Pointer part); /** * Brings a part to the front of its stack. Does not update the active part or * active editor. This should only be called if the caller knows that the part * is not in the same stack as the active part or active editor, or if the caller * is prepared to update activation after the call. * * @param part */ private: bool InternalBringToTop(IWorkbenchPartReference::Pointer part); /** * Moves a part forward in the Z order of a perspective so it is visible. * If the part is in the same stack as the active part, the new part is * activated. * * @param part * the part to bring to move forward */ public: void BringToTop(IWorkbenchPart::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. * * Assumes the busy cursor is active. */ private: void BusyResetPerspective(); /** * Implements setPerspective. * * Assumes that busy cursor is active. * * @param desc * identifies the new perspective. */ private: void BusySetPerspective(IPerspectiveDescriptor::Pointer desc); /** * Removes the perspective which match the given description. * * @param desc * identifies the perspective to be removed. */ public: void RemovePerspective(IPerspectiveDescriptor::Pointer desc); /** * Shows a view. * * Assumes that a busy cursor is active. */ protected: IViewPart::Pointer BusyShowView(const QString& viewID, const QString& secondaryID, int mode); /* * Performs showing of the view in the given mode. */ private: void BusyShowView(IViewPart::Pointer part, int mode); /** * Returns whether a part exists in the current page. */ private: bool CertifyPart(IWorkbenchPart::Pointer part); /** * Closes the perspective. */ public: bool Close(); /** * See IWorkbenchPage */ public: bool CloseAllSavedEditors(); /** * See IWorkbenchPage */ public: bool CloseAllEditors(bool save); private: void UpdateActivePart(); /** * Makes the given part active. Brings it in front if necessary. Permits null * (indicating that no part should be active). * * @since 3.1 * * @param ref new active part (or null) */ private: void MakeActive(IWorkbenchPartReference::Pointer ref); /** * Makes the given editor active. Brings it to front if necessary. Permits null * (indicating that no editor is active). * * @since 3.1 * * @param ref the editor to make active, or null for no active editor */ private: void MakeActiveEditor(IEditorReference::Pointer ref); /** * See IWorkbenchPage */ public: bool CloseEditors(const QList& refArray, bool save); /** * Enables or disables listener notifications. This is used to delay listener notifications until the * end of a public method. * * @param shouldDefer */ private: void DeferUpdates(bool shouldDefer); private: void StartDeferring(); private: void HandleDeferredEvents(); private: bool IsDeferred(); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorReference::Pointer editorRef, bool save); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorPart::Pointer editor, bool save); /** * Closes current perspective. If last perspective, then entire page * is closed. * * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ public: void CloseCurrentPerspective(bool saveParts, bool closePage); /** * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) */ public: void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage); /** * Closes the specified perspective. If last perspective, then entire page * is closed. * * @param persp * the perspective to be closed * @param saveParts * whether the parts that are being closed should be saved * (editors if last perspective, views if not shown in other * parspectives) */ /* package */ protected: void ClosePerspective(SmartPointer persp, bool saveParts, bool closePage); /** * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) */ public: void CloseAllPerspectives(bool saveEditors, bool closePage); /** * Creates the client composite. */ private: void CreateClientComposite(); /** * Creates a new view set. Return null on failure. * * @param desc the perspective descriptor * @param notify whether to fire a perspective opened event */ private: SmartPointer CreatePerspective(SmartPointer desc, bool notify); /** * This is called by child objects after a part has been added to the page. * The page will in turn notify its listeners. */ /* package */ protected: void PartAdded(WorkbenchPartReference::Pointer ref); /** * This is called by child objects after a part has been added to the page. * The part will be queued for disposal after all listeners have been notified */ /* package */ protected: void PartRemoved(WorkbenchPartReference::Pointer ref); private: void DisposePart(WorkbenchPartReference::Pointer ref); /** * Deactivates a part. The pane is unhilighted. */ private: void DeactivatePart(IWorkbenchPart::Pointer part); /** * Detaches a view from the WorkbenchWindow. */ public: void DetachView(IViewReference::Pointer ref); /** * Removes a detachedwindow. */ public: void AttachView(IViewReference::Pointer ref); /** * Dispose a perspective. * * @param persp the perspective descriptor * @param notify whether to fire a perspective closed event */ private: void DisposePerspective(SmartPointer persp, bool notify); /** * Returns the first view manager with given ID. */ public: SmartPointer FindPerspective(IPerspectiveDescriptor::Pointer desc); /** * See IWorkbenchPage@findView. */ public: IViewPart::Pointer FindView(const QString& id); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const QString& viewId); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId); /** * Notify property change listeners about a property change. * * @param changeId * the change id * @param oldValue * old property value * @param newValue * new property value */ //private: void FirePropertyChange(String changeId, Object oldValue, // Object newValue) { // // UIListenerLogging.logPagePropertyChanged(this, changeId, oldValue, newValue); // // Object[] listeners = propertyChangeListeners.getListeners(); // PropertyChangeEvent event = new PropertyChangeEvent(this, changeId, // oldValue, newValue); // // for (int i = 0; i < listeners.length; i++) { // ((IPropertyChangeListener) listeners[i]).propertyChange(event); // } // } /** * @see IWorkbenchPage */ public: IEditorPart::Pointer GetActiveEditor(); /** * Returns the reference for the active editor, or null * if there is no active editor. * * @return the active editor reference or null */ public: IEditorReference::Pointer GetActiveEditorReference(); /* * (non-Javadoc) Method declared on IPartService */ public: IWorkbenchPart::Pointer GetActivePart(); /* * (non-Javadoc) Method declared on IPartService */ public: IWorkbenchPartReference::Pointer GetActivePartReference(); /** * Returns the active perspective for the page, null if * none. */ public: SmartPointer GetActivePerspective(); /** * Returns the client composite. */ public: void* GetClientComposite(); // for dynamic UI - change access from private to protected // for testing purposes only, changed from protected to public /** * Answer the editor manager for this window. */ public: EditorManager* GetEditorManager(); /** * Answer the perspective presentation. */ public: PerspectiveHelper* GetPerspectivePresentation(); /** * Answer the editor presentation. */ public: EditorAreaHelper* GetEditorPresentation(); /** * Allow access to the part service for this page ... used internally to * propogate certain types of events to the page part listeners. * @return the part service for this page. */ public: PartService* GetPartService(); /** * See IWorkbenchPage. */ public: QList GetEditors(); public: QList GetDirtyEditors(); public: QList GetDirtyParts(); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer FindEditor(IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: QList FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags); /** * See IWorkbenchPage. */ public: QList GetEditorReferences(); /** * @see IWorkbenchPage */ public: IAdaptable* GetInput(); /** * Returns the page label. This is a combination of the page input and * active perspective. */ public: QString GetLabel(); /** * Returns the perspective. */ public: IPerspectiveDescriptor::Pointer GetPerspective(); /* * (non-Javadoc) Method declared on ISelectionService */ public: ISelection::ConstPointer GetSelection() const; /* * (non-Javadoc) Method declared on ISelectionService */ public: ISelection::ConstPointer GetSelection(const QString& partId); //public: // SelectionEvents& GetSelectionEvents(const QString& partId = ""); /* * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: QList GetViewReferences(); /** * See IWorkbenchPage. */ public: QList GetViews(); /** * Returns all view parts in the specified perspective * * @param persp the perspective * @return an array of view parts * @since 3.1 */ /*package*/ protected: QList GetViews(SmartPointer persp, bool restore); /** * See IWorkbenchPage. */ public: IWorkbenchWindow::Pointer GetWorkbenchWindow(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#hideView(org.blueberry.ui.IViewReference) */ public: void HideView(IViewReference::Pointer ref); /* package */ protected: void RefreshActiveView(); /** * See IPerspective */ public: void HideView(IViewPart::Pointer view); /** * Initialize the page. * * @param w * the parent window * @param layoutID * may be null if restoring from file * @param input * the page input * @param openExtras * whether to process the perspective extras preference */ private: void Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras); /** * Opens the perspectives specified in the PERSPECTIVE_BAR_EXTRAS preference (see bug 84226). */ public: void OpenPerspectiveExtras(); /** * See IWorkbenchPage. */ public: bool IsPartVisible(IWorkbenchPart::Pointer part); /** * See IWorkbenchPage. */ public: bool IsEditorAreaVisible(); /** * Returns whether the view is fast. */ public: bool IsFastView(IViewReference::Pointer ref); /** * Return whether the view is closeable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is closeable. * @since 3.1.1 */ public: bool IsCloseable(IViewReference::Pointer ref); /** * Return whether the view is moveable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is moveable. * @since 3.1.1 */ public: bool IsMoveable(IViewReference::Pointer ref); /** * Returns whether the layout of the active * perspective is fixed. */ public: bool IsFixedLayout(); /** * Return true if the perspective has a dirty editor. */ protected: bool IsSaveNeeded(); /** * This method is called when the page is activated. */ protected: void OnActivate(); /** * This method is called when the page is deactivated. */ protected: void OnDeactivate(); /** * See IWorkbenchPage. */ public: void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags); /** * This is not public API but for use internally. editorState can be null. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * Opens a new editor using the given input and descriptor. (Normally, editors are opened using * an editor ID and an input.) */ public: IEditorPart::Pointer OpenEditorFromDescriptor(IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); /** * @see #openEditor(IEditorInput, String, boolean, int) */ private: IEditorPart::Pointer BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ private: IEditorPart::Pointer BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); /** * Do not call this method. Use busyOpenEditor. * * @see IWorkbenchPage#openEditor(IEditorInput, String, boolean) */ protected: IEditorPart::Pointer BusyOpenEditorBatched(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ private: IEditorPart::Pointer BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); public: void OpenEmptyTab(); protected: void ShowEditor(bool activate, IEditorPart::Pointer editor); /** * See IWorkbenchPage. */ public: bool IsEditorPinned(IEditorPart::Pointer editor); /** * Removes an IPartListener from the part service. */ public: void RemovePartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(const QString& partId, ISelectionListener* listener); /** * This method is called when a part is activated by clicking within it. In * response, the part, the pane, and all of its actions will be activated. * * In the current design this method is invoked by the part pane when the * pane, the part, or any children gain focus. */ public: void RequestActivation(IWorkbenchPart::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ public: void ResetPerspective(); /** * Restore this page from the memento and ensure that the active * perspective is equals the active descriptor otherwise create a new * perspective for that descriptor. If activeDescriptor is null active the * old perspective. */ public: /*IStatus*/bool RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor); /** * See IWorkbenchPage */ public: bool SaveAllEditors(bool confirm); /** * @param confirm * @param addNonPartSources true if saveables from non-part sources should be saved too * @return false if the user cancelled * */ public: bool SaveAllEditors(bool confirm, bool addNonPartSources); /* * Saves the workbench part. */ protected: bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm); /** * Saves an editors in the workbench. If confirm is true * the user is prompted to confirm the command. * * @param confirm * if user confirmation should be sought * @return true if the command succeeded, or false * if the user cancels the command */ public: bool SaveEditor(IEditorPart::Pointer editor, bool confirm); /** * Saves the current perspective. */ public: void SavePerspective(); /** * Saves the perspective. */ public: void SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc); /** * Save the state of the page. */ public: /*IStatus*/bool SaveState(IMemento::Pointer memento); private: QString GetId(IWorkbenchPart::Pointer part); private: QString GetId(IWorkbenchPartReference::Pointer ref); /** * Sets the active part. */ private: void SetActivePart(IWorkbenchPart::Pointer newPart); /** * See IWorkbenchPage. */ public: void SetEditorAreaVisible(bool showEditorArea); /** * Sets the layout of the page. Assumes the new perspective is not null. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ private: void SetPerspective(SmartPointer newPersp); /* * Update visibility state of all views. */ private: void UpdateVisibility(SmartPointer oldPersp, SmartPointer newPersp); /** * Sets the perspective. * * @param desc * identifies the new perspective. */ public: void SetPerspective(IPerspectiveDescriptor::Pointer desc); /** * Restore the toolbar layout for the active perspective. */ protected: void ResetToolBarLayout(); /** * See IWorkbenchPage. */ public: IViewPart::Pointer ShowView(const QString& viewID); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#showView(java.lang.String, * java.lang.String, int) */ public: IViewPart::Pointer ShowView(const QString& viewID, const QString& secondaryID, int mode); /** * @param mode the mode to test * @return whether the mode is recognized * @since 3.0 */ private: bool CertifyMode(int mode); /* * Returns the editors in activation order (oldest first). */ public: QList GetSortedEditors(); /** * @see IWorkbenchPage#getOpenPerspectives() */ public: QList GetOpenPerspectives(); /** * Return all open Perspective objects. * * @return all open Perspective objects * @since 3.1 */ /*package*/ protected: QList > GetOpenInternalPerspectives(); /** * Checks perspectives in the order they were activiated * for the specfied part. The first sorted perspective * that contains the specified part is returned. * * @param part specified part to search for * @return the first sorted perspespective containing the part * @since 3.1 */ /*package*/ protected: SmartPointer GetFirstPerspectiveWithView(IViewPart::Pointer part); /** * Returns the perspectives in activation order (oldest first). */ public: QList GetSortedPerspectives(); /* * Returns the parts in activation order (oldest first). */ public: QList GetSortedParts(); /** * Returns the reference to the given part, or null if it has no reference * (i.e. it is not a top-level part in this workbench page). * * @param part the part * @return the part's reference or null if the given part does not belong * to this workbench page */ public: IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part); // private: class ActivationList { // //List of parts in the activation order (oldest first) // List parts = new ArrayList(); // // /* // * Add/Move the active part to end of the list; // */ // void setActive(IWorkbenchPart part) { // if (parts.size() <= 0) { // return; // } // IWorkbenchPartReference ref = getReference(part); // if (ref != null) { // if (ref == parts.get(parts.size() - 1)) { // return; // } // parts.remove(ref); // parts.add(ref); // } // } // // /* // * Ensures that the given part appears AFTER any other part in the same // * container. // */ // void bringToTop(IWorkbenchPartReference ref) { // ILayoutContainer targetContainer = getContainer(ref); // // int newIndex = lastIndexOfContainer(targetContainer); // // //New index can be -1 if there is no last index // if (newIndex >= 0 && ref == parts.get(newIndex)) // return; // // parts.remove(ref); // if(newIndex >= 0) // parts.add(newIndex, ref); // else // parts.add(ref); // } // // /* // * Returns the last (most recent) index of the given container in the activation list, or returns // * -1 if the given container does not appear in the activation list. // */ // int lastIndexOfContainer(ILayoutContainer container) { // for (int i = parts.size() - 1; i >= 0; i--) { // IWorkbenchPartReference ref = (IWorkbenchPartReference)parts.get(i); // // ILayoutContainer cnt = getContainer(ref); // if (cnt == container) { // return i; // } // } // // return -1; // } // // /* // * Add/Move the active part to end of the list; // */ // void setActive(IWorkbenchPartReference ref) { // setActive(ref.getPart(true)); // } // // /* // * Add the active part to the beginning of the list. // */ // void add(IWorkbenchPartReference ref) { // if (parts.indexOf(ref) >= 0) { // return; // } // // IWorkbenchPart part = ref.getPart(false); // if (part != null) { // PartPane pane = ((PartSite) part.getSite()).getPane(); // if (pane instanceof MultiEditorInnerPane) { // MultiEditorInnerPane innerPane = (MultiEditorInnerPane) pane; // add(innerPane.getParentPane().getPartReference()); // return; // } // } // parts.add(0, ref); // } // // /* // * Return the active part. Filter fast views. // */ // IWorkbenchPart getActive() { // if (parts.isEmpty()) { // return null; // } // return getActive(parts.size() - 1); // } // // /* // * Return the previously active part. Filter fast views. // */ // IWorkbenchPart getPreviouslyActive() { // if (parts.size() < 2) { // return null; // } // return getActive(parts.size() - 2); // } // // private: IWorkbenchPart getActive(int start) { // IWorkbenchPartReference ref = getActiveReference(start, false); // // if (ref == null) { // return null; // } // // return ref.getPart(true); // } // // public: IWorkbenchPartReference getActiveReference(boolean editorsOnly) { // return getActiveReference(parts.size() - 1, editorsOnly); // } // // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly) { // // First look for parts that aren't obscured by the current zoom state // IWorkbenchPartReference nonObscured = getActiveReference(start, editorsOnly, true); // // if (nonObscured != null) { // return nonObscured; // } // // // Now try all the rest of the parts // return getActiveReference(start, editorsOnly, false); // } // // /* // * Find a part in the list starting from the end and filter // * and views from other perspectives. Will filter fast views // * unless 'includeActiveFastViews' is true; // */ // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly, boolean skipPartsObscuredByZoom) { // IWorkbenchPartReference[] views = getViewReferences(); // for (int i = start; i >= 0; i--) { // WorkbenchPartReference ref = (WorkbenchPartReference) parts // .get(i); // // if (editorsOnly && !(ref instanceof IEditorReference)) { // continue; // } // // // Skip parts whose containers have disabled auto-focus // PartPane pane = ref.getPane(); // // if (pane != null) { // if (!pane.allowsAutoFocus()) { // continue; // } // // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } // } // // // Skip fastviews (unless overridden) // if (ref instanceof IViewReference) { // if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { // for (int j = 0; j < views.length; j++) { // if (views[j] == ref) { // return ref; // } // } // } // } else { // return ref; // } // } // return null; // } // // /* // * Retuns the index of the part within the activation list. The higher // * the index, the more recently it was used. // */ // int indexOf(IWorkbenchPart part) { // IWorkbenchPartReference ref = getReference(part); // if (ref == null) { // return -1; // } // return parts.indexOf(ref); // } // // /* // * Returns the index of the part reference within the activation list. // * The higher the index, the more recent it was used. // */ // int indexOf(IWorkbenchPartReference ref) { // return parts.indexOf(ref); // } // // /* // * Remove a part from the list // */ // boolean remove(IWorkbenchPartReference ref) { // return parts.remove(ref); // } // // /* // * Returns the editors in activation order (oldest first). // */ // private: IEditorReference[] getEditors() { // ArrayList editors = new ArrayList(parts.size()); // for (Iterator i = parts.iterator(); i.hasNext();) { // IWorkbenchPartReference part = (IWorkbenchPartReference) i // .next(); // if (part instanceof IEditorReference) { // editors.add(part); // } // } // return (IEditorReference[]) editors // .toArray(new IEditorReference[editors.size()]); // } // // /* // * Return a list with all parts (editors and views). // */ // private: IWorkbenchPartReference[] getParts() { // IWorkbenchPartReference[] views = getViewReferences(); // ArrayList resultList = new ArrayList(parts.size()); // for (Iterator iterator = parts.iterator(); iterator.hasNext();) { // IWorkbenchPartReference ref = (IWorkbenchPartReference) iterator // .next(); // if (ref instanceof IViewReference) { // //Filter views from other perspectives // for (int i = 0; i < views.length; i++) { // if (views[i] == ref) { // resultList.add(ref); // break; // } // } // } else { // resultList.add(ref); // } // } // IWorkbenchPartReference[] result = new IWorkbenchPartReference[resultList // .size()]; // return (IWorkbenchPartReference[]) resultList.toArray(result); // } // // /* // * Returns the topmost editor on the stack, or null if none. // */ // IEditorPart getTopEditor() { // IEditorReference editor = (IEditorReference)getActiveReference(parts.size() - 1, true); // // if (editor == null) { // return null; // } // // return editor.getEditor(true); // } // }; // for dynamic UI protected: void AddPerspective(SmartPointer persp); /** * Find the stack of view references stacked with this view part. * * @param part * the part * @return the stack of references * @since 3.0 */ private: QList GetViewReferenceStack( IViewPart::Pointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getViewStack(org.blueberry.ui.IViewPart) */ public: QList GetViewStack(IViewPart::Pointer part); /** * Allow for programmatically resizing a part. *

* EXPERIMENTAL *

*

* Known limitations: *

    *
  • currently applies only to views
  • *
  • has no effect when view is zoomed
  • *
*/ public: void ResizeView(IViewPart::Pointer part, int width, int height); private: struct ActivationOrderPred : std::binary_function { ActivationOrderPred(ActivationList* partList); ActivationList* activationList; bool operator()(const IViewReference::Pointer o1, const IViewReference::Pointer o2) const; }; // provides sash information for the given pane struct SashInfo { SmartPointer right; SmartPointer left; SmartPointer top; SmartPointer bottom; SmartPointer rightNode; SmartPointer leftNode; SmartPointer topNode; SmartPointer bottomNode; }; void FindSashParts(SmartPointer tree, const PartPane::Sashes& sashes, SashInfo& info); /** * Returns all parts that are owned by this page * * @return */ protected: QList GetAllParts(); /** * Returns all open parts that are owned by this page (that is, all parts * for which a part opened event would have been sent -- these would be * activated parts whose controls have already been created. */ protected: QList GetOpenParts(); /** * Sanity-checks the objects in this page. Throws an Assertation exception * if an object's internal state is invalid. ONLY INTENDED FOR USE IN THE * UI TEST SUITES. */ public: void TestInvariants(); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() */ //public: IExtensionTracker GetExtensionTracker(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ public: QList GetPerspectiveShortcuts(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() */ public: QList GetShowViewShortcuts(); /** * @since 3.1 */ private: void SuggestReset(); public: bool IsPartVisible(IWorkbenchPartReference::Pointer reference); }; } #endif /*BERRYWORKBENCHPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp index 9d9636899c..1d82b3c991 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp @@ -1,1964 +1,1961 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "tweaklets/berryGuiWidgetsTweaklet.h" #include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryIPerspectiveDescriptor.h" #include "berryUIException.h" #include "berryConstants.h" #include "berryIMenuService.h" #include "berryMenuUtil.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartSite.h" #include "berryIServiceLocatorCreator.h" #include "berryMenuManager.h" #include "berryQtControlWidget.h" #include "berryQtPerspectiveSwitcher.h" #include "berryWWinActionBars.h" #include "berryWorkbenchLocationService.h" #include "berryIServiceFactory.h" #include "berryIServiceScopes.h" #include "berryIEvaluationReference.h" #include "berryPlatformUI.h" #include "berryDebugUtil.h" #include #include #include namespace berry { const QString WorkbenchWindow::PROP_TOOLBAR_VISIBLE = "toolbarVisible"; const QString WorkbenchWindow::PROP_PERSPECTIVEBAR_VISIBLE = "perspectiveBarVisible"; const QString WorkbenchWindow::PROP_STATUS_LINE_VISIBLE = "statusLineVisible"; const ActionBarAdvisor::FillFlags WorkbenchWindow::FILL_ALL_ACTION_BARS = ActionBarAdvisor::FILL_MENU_BAR | ActionBarAdvisor::FILL_TOOL_BAR | ActionBarAdvisor::FILL_STATUS_LINE; WorkbenchWindow::WorkbenchWindow(int number) : Window(Shell::Pointer(0)) , pageComposite(0) , windowAdvisor(0) , actionBarAdvisor(0) , number(number) , largeUpdates(0) , closing(false) , shellActivated(false) , updateDisabled(true) , toolBarVisible(true) , perspectiveBarVisible(true) , statusLineVisible(true) , emptyWindowContentsCreated(false) , emptyWindowContents(0) , asMaximizedState(false) , partService(this) , serviceLocatorOwner(new ServiceLocatorOwner(this)) { this->Register(); // increase the reference count to avoid deleting // this object when temporary smart pointers // go out of scope // Make sure there is a workbench. This call will throw // an exception if workbench not created yet. IWorkbench* workbench = PlatformUI::GetWorkbench(); IServiceLocatorCreator* slc = workbench->GetService(); this->serviceLocator = slc->CreateServiceLocator( workbench, nullptr, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); InitializeDefaultServices(); // Add contribution managers that are exposed to other plugins. this->AddMenuBar(); //addCoolBar(SWT.NONE); // style is unused //addStatusLine(); this->FireWindowOpening(); // Fill the action bars this->FillActionBars(FILL_ALL_ACTION_BARS); this->UnRegister(false); // decrease reference count and avoid deleting // the window } WorkbenchWindow::~WorkbenchWindow() { //BERRY_INFO << "WorkbenchWindow::~WorkbenchWindow()"; } Object* WorkbenchWindow::GetService(const QString& key) { return serviceLocator->GetService(key); } bool WorkbenchWindow::HasService(const QString& key) const { return serviceLocator->HasService(key); } Shell::Pointer WorkbenchWindow::GetShell() const { return Window::GetShell(); } bool WorkbenchWindow::ClosePage(IWorkbenchPage::Pointer in, bool save) { // Validate the input. if (!pageList.Contains(in)) { return false; } WorkbenchPage::Pointer oldPage = in.Cast (); // Save old perspective. if (save && oldPage->IsSaveNeeded()) { if (!oldPage->SaveAllEditors(true)) { return false; } } // If old page is activate deactivate. bool oldIsActive = (oldPage == this->GetActivePage()); if (oldIsActive) { this->SetActivePage(IWorkbenchPage::Pointer(0)); } // Close old page. pageList.Remove(oldPage); partService.PageClosed(oldPage); //this->FirePageClosed(oldPage); //oldPage->Dispose(); // Activate new page. if (oldIsActive) { IWorkbenchPage::Pointer newPage = pageList.GetNextActive(); if (newPage != 0) { this->SetActivePage(newPage); } } if (!closing && pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } return true; } void WorkbenchWindow::AddPerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.AddListener(l); } void WorkbenchWindow::RemovePerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.RemoveListener(l); } IPerspectiveListener::Events& WorkbenchWindow::GetPerspectiveEvents() { return perspectiveEvents; } void WorkbenchWindow::FireWindowOpening() { // let the application do further configuration this->GetWindowAdvisor()->PreWindowOpen(); } void WorkbenchWindow::FireWindowRestored() { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->GetWindowAdvisor()->PostWindowRestore(); // } //}); } void WorkbenchWindow::FireWindowCreated() { this->GetWindowAdvisor()->PostWindowCreate(); } void WorkbenchWindow::FireWindowOpened() { this->GetWorkbenchImpl()->FireWindowOpened(IWorkbenchWindow::Pointer(this)); this->GetWindowAdvisor()->PostWindowOpen(); } bool WorkbenchWindow::FireWindowShellClosing() { return this->GetWindowAdvisor()->PreWindowShellClose(); } void WorkbenchWindow::FireWindowClosed() { // let the application do further deconfiguration this->GetWindowAdvisor()->PostWindowClose(); this->GetWorkbenchImpl()->FireWindowClosed(IWorkbenchWindow::Pointer(this)); } ///** // * Fires page activated // */ //void WorkbenchWindow::FirePageActivated(IWorkbenchPage::Pointer page) { //// String label = null; // debugging only //// if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { //// label = "activated " + page.getLabel(); //$NON-NLS-1$ //// } //// try { //// UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); //// UIListenerLogging.logPageEvent(this, page, //// UIListenerLogging.WPE_PAGE_ACTIVATED); // pageEvents.FirePageActivated(page); // partService.pageActivated(page); //// } finally { //// UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); //// } //} // ///** // * Fires page closed // */ //void WorkbenchWindow::FirePageClosed(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "closed " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_CLOSED); // pageListeners.firePageClosed(page); // partService.pageClosed(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } // //} // ///** // * Fires page opened // */ //void WorkbenchWindow::FirePageOpened(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "opened " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_OPENED); // pageListeners.firePageOpened(page); // partService.pageOpened(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } //} void WorkbenchWindow::FirePerspectiveActivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_ACTIVATED); perspectiveEvents.perspectiveActivated(page, perspective); } void WorkbenchWindow::FirePerspectivePreDeactivate( IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_PRE_DEACTIVATE); perspectiveEvents.perspectivePreDeactivate(page, perspective); } void WorkbenchWindow::FirePerspectiveDeactivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_DEACTIVATED); perspectiveEvents.perspectiveDeactivated(page, perspective); } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, null, changeId); perspectiveEvents.perspectiveChanged(page, perspective, changeId); } } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, partRef, changeId); perspectiveEvents.perspectivePartChanged(page, perspective, partRef, changeId); } } void WorkbenchWindow::FirePerspectiveClosed(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_CLOSED); perspectiveEvents.perspectiveClosed(page, perspective); } void WorkbenchWindow::FirePerspectiveOpened(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_OPENED); perspectiveEvents.perspectiveOpened(page, perspective); } void WorkbenchWindow::FirePerspectiveSavedAs(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer oldPerspective, IPerspectiveDescriptor::Pointer newPerspective) { // UIListenerLogging.logPerspectiveSavedAs(this, page, oldPerspective, // newPerspective); perspectiveEvents.perspectiveSavedAs(page, oldPerspective, newPerspective); } void WorkbenchWindow::FillActionBars(ActionBarAdvisor::FillFlags flags) { // Workbench workbench = getWorkbenchImpl(); // workbench.largeUpdateStart(); //try { this->GetActionBarAdvisor()->FillActionBars(flags); IMenuService* menuService = serviceLocator->GetService(); menuService->PopulateContributionManager(dynamic_cast(GetActionBars()->GetMenuManager()), MenuUtil::MAIN_MENU); // ICoolBarManager coolbar = getActionBars().getCoolBarManager(); // if (coolbar != null) // { // menuService.populateContributionManager( // (ContributionManager) coolbar, // MenuUtil.MAIN_TOOLBAR); // } // } finally { // workbench.largeUpdateEnd(); // } } Point WorkbenchWindow::GetInitialSize() { return this->GetWindowConfigurer()->GetInitialSize(); } bool WorkbenchWindow::Close() { //BERRY_INFO << "WorkbenchWindow::Close()"; if (controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(GetShell()->GetControl(), controlResizeListener); } bool ret = false; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(); // } // }); if (!ret && controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(GetShell()->GetControl(), controlResizeListener); } return ret; } bool WorkbenchWindow::BusyClose() { // Whether the window was actually closed or not bool windowClosed = false; // Setup internal flags to indicate window is in // progress of closing and no update should be done. closing = true; updateDisabled = true; try { // Only do the check if it is OK to close if we are not closing // via the workbench as the workbench will check this itself. Workbench* workbench = this->GetWorkbenchImpl(); std::size_t count = workbench->GetWorkbenchWindowCount(); // also check for starting - if the first window dies on startup // then we'll need to open a default window. if (!workbench->IsStarting() && !workbench->IsClosing() && count <= 1 && workbench->GetWorkbenchConfigurer() ->GetExitOnLastWindowClose()) { windowClosed = workbench->Close(); } else { if (this->OkToClose()) { windowClosed = this->HardClose(); } } } catch (std::exception& exc) { if (!windowClosed) { // Reset the internal flags if window was not closed. closing = false; updateDisabled = false; } throw exc; } // if (windowClosed && tracker != null) { // tracker.close(); // } return windowClosed; } void WorkbenchWindow::MakeVisible() { Shell::Pointer shell = GetShell(); if (shell) { // see bug 96700 and bug 4414 for a discussion on the use of open() // here shell->Open(); } } bool WorkbenchWindow::OkToClose() { // Save all of the editors. if (!this->GetWorkbenchImpl()->IsClosing()) { if (!this->SaveAllPages(true)) { return false; } } return true; } bool WorkbenchWindow::SaveAllPages(bool bConfirm) { bool bRet = true; PageList::iterator itr = pageList.Begin(); while (bRet && itr != pageList.End()) { bRet = (*itr)->SaveAllEditors(bConfirm); ++itr; } return bRet; } bool WorkbenchWindow::HardClose() { std::exception exc; bool exceptionOccured = false; try { // Clear the action sets, fix for bug 27416. //getActionPresentation().clearActionSets(); // Remove the handler submissions. Bug 64024. /* final IWorkbench workbench = getWorkbench(); final IHandlerService handlerService = (IHandlerService) workbench.getService(IHandlerService.class); handlerService.deactivateHandlers(handlerActivations); final Iterator activationItr = handlerActivations.iterator(); while (activationItr.hasNext()) { final IHandlerActivation activation = (IHandlerActivation) activationItr .next(); activation.getHandler().dispose(); } handlerActivations.clear(); globalActionHandlersByCommandId.clear(); */ // Remove the enabled submissions. Bug 64024. /* final IContextService contextService = (IContextService) workbench.getService(IContextService.class); contextService.unregisterShell(getShell()); */ this->CloseAllPages(); this->FireWindowClosed(); // time to wipe out our populate /* IMenuService menuService = (IMenuService) workbench .getService(IMenuService.class); menuService .releaseContributions(((ContributionManager) getActionBars() .getMenuManager())); ICoolBarManager coolbar = getActionBars().getCoolBarManager(); if (coolbar != null) { menuService .releaseContributions(((ContributionManager) coolbar)); } */ //getActionBarAdvisor().dispose(); //getWindowAdvisor().dispose(); //detachedWindowShells.dispose(); delete windowAdvisor; windowAdvisor = 0; // Null out the progress region. Bug 64024. //progressRegion = null; // Remove drop targets /* DragUtil.removeDragTarget(null, trimDropTarget); DragUtil.removeDragTarget(getShell(), trimDropTarget); trimDropTarget = null; if (trimMgr2 != null) { trimMgr2.dispose(); trimMgr2 = null; } if (trimContributionMgr != null) { trimContributionMgr.dispose(); trimContributionMgr = null; } */ } catch (std::exception& e) { exc = e; exceptionOccured = true; } bool result = Window::Close(); // Bring down all of the services ... after the window goes away serviceLocator->Dispose(); //menuRestrictions.clear(); if (exceptionOccured) throw exc; return result; } void WorkbenchWindow::CloseAllPages() { // Deactivate active page. this->SetActivePage(IWorkbenchPage::Pointer(0)); // Clone and deref all so that calls to getPages() returns // empty list (if called by pageClosed event handlers) PageList oldList = pageList; pageList.Clear(); // Close all. for (PageList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { partService.PageClosed(*itr); //(*itr)->FirePageClosed(page); //page.dispose(); } if (!closing) { this->ShowEmptyWindowContents(); } } WWinActionBars* WorkbenchWindow::GetActionBars() { if (actionBars.IsNull()) { actionBars = new WWinActionBars(this); } return actionBars.GetPointer(); } -void WorkbenchWindow::SetPerspectiveExcludeList(std::vector v) +void WorkbenchWindow::SetPerspectiveExcludeList(const QStringList& v) { - perspectiveExcludeList = v; + perspectiveExcludeList = v; } -std::vector WorkbenchWindow::GetPerspectiveExcludeList() +QStringList WorkbenchWindow::GetPerspectiveExcludeList() const { - return perspectiveExcludeList; + return perspectiveExcludeList; } -void WorkbenchWindow::SetViewExcludeList(std::vector v) +void WorkbenchWindow::SetViewExcludeList(const QStringList& v) { - viewExcludeList = v; + viewExcludeList = v; } -std::vector WorkbenchWindow::GetViewExcludeList() +QStringList WorkbenchWindow::GetViewExcludeList() const { - return viewExcludeList; + return viewExcludeList; } -IWorkbenchPage::Pointer WorkbenchWindow::GetPage(int i) +IWorkbenchPage::Pointer WorkbenchWindow::GetPage(int i) const { - std::list pages = pageList.GetPages(); - std::list::iterator it; - int j=-1; - for (it = pages.begin(); it!=pages.end(); it++) + QList pages = pageList.GetPages(); + int j = 0; + for (auto it = pages.begin(); it!=pages.end(); it++, j++) + { + if (j==i) { - j++; - if (j==i) - break; + return *it; } - if (j==i) - return *it; - - return IWorkbenchPage::Pointer(); + } + return IWorkbenchPage::Pointer(); } IWorkbenchPage::Pointer WorkbenchWindow::GetActivePage() const { return pageList.GetActive(); } IWorkbench* WorkbenchWindow::GetWorkbench() { return PlatformUI::GetWorkbench(); } IPartService* WorkbenchWindow::GetPartService() { return &partService; } ISelectionService* WorkbenchWindow::GetSelectionService() { return partService.GetSelectionService(); } bool WorkbenchWindow::GetToolBarVisible() const { return GetWindowConfigurer()->GetShowToolBar() && toolBarVisible; } bool WorkbenchWindow::GetPerspectiveBarVisible() const { return GetWindowConfigurer()->GetShowPerspectiveBar() && perspectiveBarVisible; } bool WorkbenchWindow::GetStatusLineVisible() const { return GetWindowConfigurer()->GetShowStatusLine() && statusLineVisible; } void WorkbenchWindow::AddPropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.AddListener(listener); } void WorkbenchWindow::RemovePropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.RemoveListener(listener); } bool WorkbenchWindow::IsClosing() { return closing || this->GetWorkbenchImpl()->IsClosing(); } int WorkbenchWindow::Open() { if (pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } this->FireWindowCreated(); this->GetWindowAdvisor()->OpenIntro(); int result = Window::Open(); // It's time for a layout ... to insure that if TrimLayout // is in play, it updates all of the trim it's responsible // for. We have to do this before updating in order to get // the PerspectiveBar management correct...see defect 137334 //getShell().layout(); this->FireWindowOpened(); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.updatePerspectiveBar(); // perspectiveSwitcher.updateBarParent(); // } return result; } void* WorkbenchWindow::GetPageComposite() { return pageComposite; } QWidget *WorkbenchWindow::CreatePageComposite(QWidget *parent) { QtControlWidget* pageArea = new QtControlWidget(parent, 0); pageArea->setObjectName("Page Composite"); new QHBoxLayout(pageArea); if (qobject_cast (parent) != 0) qobject_cast (parent)->setCentralWidget(pageArea); else parent->layout()->addWidget(pageArea); // we have to enable visibility to get a proper layout (see bug #1654) pageArea->setVisible(true); parent->setVisible(true); pageComposite = pageArea; return pageArea; } void* WorkbenchWindow::CreateContents(Shell::Pointer parent) { // we know from Window.create that the parent is a Shell. this->GetWindowAdvisor()->CreateWindowContents(parent); // the page composite must be set by createWindowContents poco_assert(pageComposite != 0) ; // "createWindowContents must call configurer.createPageComposite"); //$NON-NLS-1$ return pageComposite; } void WorkbenchWindow::CreateDefaultContents(Shell::Pointer shell) { QMainWindow* mainWindow = qobject_cast(shell->GetControl()); if (GetWindowConfigurer()->GetShowMenuBar() && mainWindow) { QMenuBar* menuBar = GetMenuBarManager()->CreateMenuBar(mainWindow); mainWindow->setMenuBar(menuBar); } if (GetWindowConfigurer()->GetShowPerspectiveBar() && mainWindow) { mainWindow->addToolBar(new QtPerspectiveSwitcher(IWorkbenchWindow::Pointer(this))); } // Create the client composite area (where page content goes). CreatePageComposite(shell->GetControl()); } void WorkbenchWindow::CreateTrimWidgets(SmartPointer /*shell*/) { // do nothing -- trim widgets are created in CreateDefaultContents } bool WorkbenchWindow::UnableToRestorePage(IMemento::Pointer pageMem) { QString pageName; pageMem->GetString(WorkbenchConstants::TAG_LABEL, pageName); // return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.WorkbenchWindow_unableToRestorePerspective, // pageName), null); WorkbenchPlugin::Log("Unable to restore perspective: " + pageName); return false; } bool WorkbenchWindow::RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor) { //TODO WorkbenchWindow restore state poco_assert(GetShell()); // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsRestoringWindow, null); bool result = true; // Restore the window advisor state. IMemento::Pointer windowAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); if (windowAdvisorState) { //result.add(getWindowAdvisor().restoreState(windowAdvisorState)); result &= GetWindowAdvisor()->RestoreState(windowAdvisorState); } // Restore actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); if (actionBarAdvisorState) { // result.add(getActionBarAdvisor() // .restoreState(actionBarAdvisorState)); result &= GetActionBarAdvisor() ->RestoreState(actionBarAdvisorState); } // Read window's bounds and state. Rectangle displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); Rectangle shellBounds; // final IMemento fastViewMem = memento // .getChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewMem != null) { // if (fastViewBar != null) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // fastViewBar.restoreState(fastViewMem); // }}); // // } // } memento->GetInteger(WorkbenchConstants::TAG_X, shellBounds.x); memento->GetInteger(WorkbenchConstants::TAG_Y, shellBounds.y); memento->GetInteger(WorkbenchConstants::TAG_WIDTH, shellBounds.width); memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, shellBounds.height); if (!shellBounds.IsEmpty()) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { if (!shellBounds.Intersects(displayBounds)) { Rectangle clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); shellBounds.x = clientArea.x; shellBounds.y = clientArea.y; } GetShell()->SetBounds(shellBounds); // }}); } QString maximized; memento->GetString(WorkbenchConstants::TAG_MAXIMIZED, maximized); if (maximized == "true") { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { GetShell()->SetMaximized(true); // }}); } QString minimized; memento->GetString(WorkbenchConstants::TAG_MINIMIZED, minimized); if (minimized == "true") { // getShell().setMinimized(true); } // // restore the width of the perspective bar // if (perspectiveSwitcher != null) { // perspectiveSwitcher.restoreState(memento); // } // // Restore the cool bar order by creating all the tool bar contribution // // items // // This needs to be done before pages are created to ensure proper // // canonical creation // // of cool items // final ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // IMemento coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMem != null) { // // Check if the layout is locked // final Integer lockedInt = coolBarMem // .getInteger(IWorkbenchConstants.TAG_LOCKED); // StartupThreading.runWithoutExceptions(new StartupRunnable(){ // // public void runWithException() { // if ((lockedInt != null) && (lockedInt.intValue() == 1)) { // coolBarMgr.setLockLayout(true); // } else { // coolBarMgr.setLockLayout(false); // } // }}); // // // The new layout of the cool bar manager // ArrayList coolBarLayout = new ArrayList(); // // Traverse through all the cool item in the memento // IMemento contributionMems[] = coolBarMem // .getChildren(IWorkbenchConstants.TAG_COOLITEM); // for (int i = 0; i < contributionMems.length; i++) { // IMemento contributionMem = contributionMems[i]; // String type = contributionMem // .getString(IWorkbenchConstants.TAG_ITEM_TYPE); // if (type == null) { // // Do not recognize that type // continue; // } // String id = contributionMem // .getString(IWorkbenchConstants.TAG_ID); // // // Prevent duplicate items from being read back in. // IContributionItem existingItem = coolBarMgr.find(id); // if ((id != null) && (existingItem != null)) { // if (Policy.DEBUG_TOOLBAR_DISPOSAL) { // System.out // .println("Not loading duplicate cool bar item: " + id); //$NON-NLS-1$ // } // coolBarLayout.add(existingItem); // continue; // } // IContributionItem newItem = null; // if (type.equals(IWorkbenchConstants.TAG_TYPE_SEPARATOR)) { // if (id != null) { // newItem = new Separator(id); // } else { // newItem = new Separator(); // } // } else if (id != null) { // if (type // .equals(IWorkbenchConstants.TAG_TYPE_GROUPMARKER)) { // newItem = new GroupMarker(id); // // } else if (type // .equals(IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION) // || type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // // // Get Width and height // Integer width = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_X); // Integer height = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_Y); // // Look for the object in the current cool bar // // manager // IContributionItem oldItem = coolBarMgr.find(id); // // If a tool bar contribution item already exists // // for this id then use the old object // if (oldItem != null) { // newItem = oldItem; // } else { // IActionBarPresentationFactory actionBarPresentation = getActionBarPresentationFactory(); // newItem = actionBarPresentation.createToolBarContributionItem( // actionBarPresentation.createToolBarManager(), id); // if (type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // IToolBarContributionItem newToolBarItem = (IToolBarContributionItem) newItem; // if (height != null) { // newToolBarItem.setCurrentHeight(height // .intValue()); // } // if (width != null) { // newToolBarItem.setCurrentWidth(width // .intValue()); // } // newItem = new PlaceholderContributionItem( // newToolBarItem); // } // // make it invisible by default // newItem.setVisible(false); // // Need to add the item to the cool bar manager // // so that its canonical order can be preserved // IContributionItem refItem = findAlphabeticalOrder( // IWorkbenchActionConstants.MB_ADDITIONS, // id, coolBarMgr); // if (refItem != null) { // coolBarMgr.insertAfter(refItem.getId(), // newItem); // } else { // coolBarMgr.add(newItem); // } // } // // Set the current height and width // if ((width != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentWidth(width.intValue()); // } // if ((height != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentHeight(height.intValue()); // } // } // } // // Add new item into cool bar manager // if (newItem != null) { // coolBarLayout.add(newItem); // newItem.setParent(coolBarMgr); // coolBarMgr.markDirty(); // } // } // // // We need to check if we have everything we need in the layout. // boolean newlyAddedItems = false; // IContributionItem[] existingItems = coolBarMgr.getItems(); // for (int i = 0; i < existingItems.length && !newlyAddedItems; i++) { // IContributionItem existingItem = existingItems[i]; // // /* // * This line shouldn't be necessary, but is here for // * robustness. // */ // if (existingItem == null) { // continue; // } // // boolean found = false; // Iterator layoutItemItr = coolBarLayout.iterator(); // while (layoutItemItr.hasNext()) { // IContributionItem layoutItem = (IContributionItem) layoutItemItr // .next(); // if ((layoutItem != null) // && (layoutItem.equals(existingItem))) { // found = true; // break; // } // } // // if (!found) { // if (existingItem != null) { // newlyAddedItems = true; // } // } // } // // // Set the cool bar layout to the given layout. // if (!newlyAddedItems) { // final IContributionItem[] itemsToSet = new IContributionItem[coolBarLayout // .size()]; // coolBarLayout.toArray(itemsToSet); // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // coolBarMgr.setItems(itemsToSet); // } // }); // } // // } else { // // For older workbenchs // coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_TOOLBAR_LAYOUT); // if (coolBarMem != null) { // // Restore an older layout // restoreOldCoolBar(coolBarMem); // } // } // } // Recreate each page in the window. IWorkbenchPage::Pointer newActivePage; QList pageArray = memento ->GetChildren(WorkbenchConstants::TAG_PAGE); for (int i = 0; i < pageArray.size(); i++) { IMemento::Pointer pageMem = pageArray[i]; QString strFocus; pageMem->GetString(WorkbenchConstants::TAG_FOCUS, strFocus); if (strFocus.isEmpty()) { continue; } // Get the input factory. IAdaptable* input = 0; IMemento::Pointer inputMem = pageMem->GetChild(WorkbenchConstants::TAG_INPUT); if (inputMem) { QString factoryID; inputMem->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryID); if (factoryID.isEmpty()) { WorkbenchPlugin ::Log("Unable to restore page - no input factory ID."); //result.add(unableToRestorePage(pageMem)); result &= UnableToRestorePage(pageMem); continue; } // try { // UIStats.start(UIStats.RESTORE_WORKBENCH, // "WorkbenchPageFactory"); //$NON-NLS-1$ // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // IElementFactory factory = PlatformUI // .getWorkbench().getElementFactory( // factoryID); // if (factory == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input factory: " + factoryID); //$NON-NLS-1$ // result // .add(unableToRestorePage(pageMem)); // return; // } // // // Get the input element. // input[0] = factory.createElement(inputMem); // } // }); // // if (input[0] == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input element: " + factoryID); //$NON-NLS-1$ // result.add(unableToRestorePage(pageMem)); // continue; // } // } finally { // UIStats.end(UIStats.RESTORE_WORKBENCH, factoryID, // "WorkbenchPageFactory"); //$NON-NLS-1$ // } } // Open the perspective. IAdaptable* finalInput = input; WorkbenchPage::Pointer newPage; try { // StartupThreading.runWithWorkbenchExceptions(new StartupRunnable(){ // // public void runWithException() throws WorkbenchException { newPage = new WorkbenchPage(this, finalInput); // }}); //result.add(newPage[0].restoreState(pageMem, activeDescriptor)); result &= newPage->RestoreState(pageMem, activeDescriptor); pageList.Add(newPage); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { partService.PageOpened(newPage); // firePageOpened(newPage[0]); // }}); } catch (const WorkbenchException& e) { WorkbenchPlugin::Log( "Unable to restore perspective - constructor failed.", e); //$NON-NLS-1$ //result.add(e.getStatus()); continue; } if (!strFocus.isEmpty()) { newActivePage = newPage; } } // If there are no pages create a default. if (pageList.IsEmpty()) { try { const QString defPerspID = this->GetWorkbenchImpl()->GetPerspectiveRegistry() ->GetDefaultPerspective(); if (!defPerspID.isEmpty()) { WorkbenchPage::Pointer newPage; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newPage = new WorkbenchPage(this, defPerspID, this->GetDefaultPageInput()); // }}); pageList.Add(newPage); //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // firePageOpened(newPage[0]); partService.PageOpened(newPage); // }}); } } catch (WorkbenchException& e) { WorkbenchPlugin ::Log( "Unable to create default perspective - constructor failed.", e); result = false; //TODO set product name // String productName = WorkbenchPlugin.getDefault() // .getProductName(); // if (productName == null) { // productName = ""; //$NON-NLS-1$ // } // getShell().setText(productName); } } // Set active page. if (newActivePage.IsNull()) { newActivePage = pageList.GetNextActive().Cast(); } //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->SetActivePage(newActivePage); // }}); IMemento::Pointer introMem = memento->GetChild(WorkbenchConstants::TAG_INTRO); if (introMem) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { bool isStandby = false; introMem->GetBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); GetWorkbench()->GetIntroManager()->ShowIntro( IWorkbenchWindow::Pointer(this), isStandby); // } // }); } // // // Only restore the trim state if we're using the default layout // if (defaultLayout != null) { // // Restore the trim state. We pass in the 'root' // // memento since we have to check for pre-3.2 // // state. // result.add(restoreTrimState(memento)); // } return result; } IAdaptable* WorkbenchWindow::GetDefaultPageInput() { return this->GetWorkbenchImpl()->GetDefaultPageInput(); } IWorkbenchPage::Pointer WorkbenchWindow::OpenPage( const QString& perspId, IAdaptable* input) { // Run op in busy cursor. IWorkbenchPage::Pointer result; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { result = this->BusyOpenPage(perspId, input); // } return result; } SmartPointer WorkbenchWindow::OpenPage(IAdaptable* input) { QString perspId = this->GetWorkbenchImpl()->GetDefaultPerspectiveId(); return this->OpenPage(perspId, input); } IWorkbenchPage::Pointer WorkbenchWindow::BusyOpenPage( const QString& perspID, IAdaptable* input) { IWorkbenchPage::Pointer newPage; if (pageList.IsEmpty()) { newPage = new WorkbenchPage(this, perspID, input); pageList.Add(newPage); //this->FirePageOpened(newPage); partService.PageOpened(newPage); this->SetActivePage(newPage); } else { IWorkbenchWindow::Pointer window = this->GetWorkbench()->OpenWorkbenchWindow(perspID, input); newPage = window->GetActivePage(); } return newPage; } int WorkbenchWindow::GetNumber() { return number; } void WorkbenchWindow::UpdateActionBars() { if (updateDisabled || UpdatesDeferred()) { return; } // updateAll required in order to enable accelerators on pull-down menus GetMenuBarManager()->Update(false); //GetToolBarManager()->Update(false); //GetStatusLineManager()->Update(false); } void WorkbenchWindow::LargeUpdateStart() { largeUpdates++; } void WorkbenchWindow::LargeUpdateEnd() { if (--largeUpdates == 0) { this->UpdateActionBars(); } } void WorkbenchWindow::SetActivePage(IWorkbenchPage::Pointer in) { if (this->GetActivePage() == in) { return; } // 1FVGTNR: ITPUI:WINNT - busy cursor for switching perspectives //BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { // public void run() { // Deactivate old persp. WorkbenchPage::Pointer currentPage = pageList.GetActive(); if (currentPage.IsNotNull()) { currentPage->OnDeactivate(); } // Activate new persp. if (in.IsNull() || pageList.Contains(in)) { pageList.SetActive(in); } WorkbenchPage::Pointer newPage = pageList.GetActive(); //Composite parent = getPageComposite(); //StackLayout layout = (StackLayout) parent.getLayout(); if (newPage.IsNotNull()) { //layout.topControl = newPage.getClientComposite(); //parent.layout(); this->HideEmptyWindowContents(); newPage->OnActivate(); //this->FirePageActivated(newPage); partService.PageActivated(newPage); //TODO perspective if (newPage->GetPerspective() != 0) { this->FirePerspectiveActivated(newPage, newPage->GetPerspective()); } } else { //layout.topControl = null; //parent.layout(); } //updateFastViewBar(); if (this->IsClosing()) { return; } updateDisabled = false; // Update action bars ( implicitly calls updateActionBars() ) //updateActionSets(); //submitGlobalActions(); //if (perspectiveSwitcher != null) { // perspectiveSwitcher.update(false); //} //getMenuManager().update(IAction.TEXT); // } //}); } MenuManager *WorkbenchWindow::GetMenuManager() const { return this->GetMenuBarManager(); } bool WorkbenchWindow::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsSavingWindow, null); bool result = true; // Save the window's state and bounds. if (GetShell()->GetMaximized() || asMaximizedState) { memento->PutString(WorkbenchConstants::TAG_MAXIMIZED, "true"); } if (GetShell()->GetMinimized()) { memento->PutString(WorkbenchConstants::TAG_MINIMIZED, "true"); } if (normalBounds.IsEmpty()) { normalBounds = GetShell()->GetBounds(); } // IMemento fastViewBarMem = memento // .createChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewBar != null) { // fastViewBar.saveState(fastViewBarMem); // } memento->PutInteger(WorkbenchConstants::TAG_X, normalBounds.x); memento->PutInteger(WorkbenchConstants::TAG_Y, normalBounds.y); memento->PutInteger(WorkbenchConstants::TAG_WIDTH, normalBounds.width); memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, normalBounds.height); IWorkbenchPage::Pointer activePage = GetActivePage(); if (activePage && activePage->FindView(IntroConstants::INTRO_VIEW_ID)) { IMemento::Pointer introMem = memento ->CreateChild(WorkbenchConstants::TAG_INTRO); bool isStandby = GetWorkbench()->GetIntroManager() ->IsIntroStandby(GetWorkbench()->GetIntroManager()->GetIntro()); introMem->PutBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); } // // save the width of the perspective bar // IMemento persBarMem = memento // .createChild(IWorkbenchConstants.TAG_PERSPECTIVE_BAR); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.saveState(persBarMem); // } // // / Save the order of the cool bar contribution items // ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // coolBarMgr.refresh(); // IMemento coolBarMem = memento // .createChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMgr.getLockLayout() == true) { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 1); // } else { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 0); // } // IContributionItem[] items = coolBarMgr.getItems(); // for (int i = 0; i < items.length; i++) { // IMemento coolItemMem = coolBarMem // .createChild(IWorkbenchConstants.TAG_COOLITEM); // IContributionItem item = items[i]; // // The id of the contribution item // if (item.getId() != null) { // coolItemMem.putString(IWorkbenchConstants.TAG_ID, item // .getId()); // } // // Write out type and size if applicable // if (item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_SEPARATOR); // } else if (item.isGroupMarker() && !item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_GROUPMARKER); // } else { // if (item instanceof PlaceholderContributionItem) { // coolItemMem.putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_PLACEHOLDER); // } else { // // Store the identifier. // coolItemMem // .putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION); // } // // /* // * Retrieve a reasonable approximation of the height and // * width, if possible. // */ // final int height; // final int width; // if (item instanceof IToolBarContributionItem) { // IToolBarContributionItem toolBarItem = (IToolBarContributionItem) item; // toolBarItem.saveWidgetState(); // height = toolBarItem.getCurrentHeight(); // width = toolBarItem.getCurrentWidth(); // } else if (item instanceof PlaceholderContributionItem) { // PlaceholderContributionItem placeholder = (PlaceholderContributionItem) item; // height = placeholder.getHeight(); // width = placeholder.getWidth(); // } else { // height = -1; // width = -1; // } // // // Store the height and width. // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_X, // width); // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_Y, // height); // } // } // } // Save each page. for (PageList::iterator itr = pageList.Begin(); itr != pageList.End(); ++itr) { WorkbenchPage::Pointer page = itr->Cast(); // Save perspective. IMemento::Pointer pageMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); pageMem->PutString(WorkbenchConstants::TAG_LABEL, page->GetLabel()); //result.add(page.saveState(pageMem)); result &= page->SaveState(pageMem); if (page == GetActivePage().Cast()) { pageMem->PutString(WorkbenchConstants::TAG_FOCUS, "true"); } // // Get the input. // IAdaptable* input = page->GetInput(); // if (input != 0) { // IPersistableElement persistable = (IPersistableElement) Util.getAdapter(input, // IPersistableElement.class); // if (persistable == null) { // WorkbenchPlugin // .log("Unable to save page input: " //$NON-NLS-1$ // + input // + ", because it does not adapt to IPersistableElement"); //$NON-NLS-1$ // } else { // // Save input. // IMemento inputMem = pageMem // .createChild(IWorkbenchConstants.TAG_INPUT); // inputMem.putString(IWorkbenchConstants.TAG_FACTORY_ID, // persistable.getFactoryId()); // persistable.saveState(inputMem); // } // } } // Save window advisor state. IMemento::Pointer windowAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); //result.add(getWindowAdvisor().saveState(windowAdvisorState)); result &= GetWindowAdvisor()->SaveState(windowAdvisorState); // Save actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); //result.add(getActionBarAdvisor().saveState(actionBarAdvisorState)); result &= GetActionBarAdvisor()->SaveState(actionBarAdvisorState); // // Only save the trim state if we're using the default layout // if (defaultLayout != null) { // IMemento trimState = memento.createChild(IWorkbenchConstants.TAG_TRIM); // result.add(saveTrimState(trimState)); // } return result; } WorkbenchWindowConfigurer::Pointer WorkbenchWindow::GetWindowConfigurer() const { if (windowConfigurer.IsNull()) { // lazy initialize windowConfigurer = new WorkbenchWindowConfigurer(WorkbenchWindow::Pointer(const_cast(this))); } return windowConfigurer; } bool WorkbenchWindow::CanHandleShellCloseEvent() { if (!Window::CanHandleShellCloseEvent()) { return false; } // let the advisor or other interested parties // veto the user's explicit request to close the window return FireWindowShellClosing(); } void WorkbenchWindow::ConfigureShell(Shell::Pointer shell) { Window::ConfigureShell(shell); detachedWindowShells = new ShellPool(shell, Constants::TITLE | Constants::MAX | Constants::CLOSE | Constants::RESIZE | Constants::BORDER ); QString title = this->GetWindowConfigurer()->BasicGetTitle(); if (!title.isEmpty()) { shell->SetText(title); } // final IWorkbench workbench = getWorkbench(); // workbench.getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.WORKBENCH_WINDOW); // final IContextService contextService = (IContextService) getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); this->TrackShellActivation(shell); this->TrackShellResize(shell); } ShellPool::Pointer WorkbenchWindow::GetDetachedWindowPool() { return detachedWindowShells; } WorkbenchAdvisor* WorkbenchWindow::GetAdvisor() { return this->GetWorkbenchImpl()->GetAdvisor(); } WorkbenchWindowAdvisor* WorkbenchWindow::GetWindowAdvisor() { if (windowAdvisor == 0) { windowAdvisor = this->GetAdvisor()->CreateWorkbenchWindowAdvisor(this->GetWindowConfigurer()); poco_check_ptr(windowAdvisor); } return windowAdvisor; } ActionBarAdvisor::Pointer WorkbenchWindow::GetActionBarAdvisor() { if (actionBarAdvisor.IsNull()) { actionBarAdvisor = this->GetWindowAdvisor()->CreateActionBarAdvisor(this->GetWindowConfigurer()->GetActionBarConfigurer()); poco_assert(actionBarAdvisor.IsNotNull()); } return actionBarAdvisor; } Workbench* WorkbenchWindow::GetWorkbenchImpl() { return dynamic_cast(this->GetWorkbench()); } void WorkbenchWindow::ShowEmptyWindowContents() { if (!emptyWindowContentsCreated) { void* parent = this->GetPageComposite(); emptyWindowContents = this->GetWindowAdvisor()->CreateEmptyWindowContents( parent); emptyWindowContentsCreated = true; // // force the empty window composite to be layed out // ((StackLayout) parent.getLayout()).topControl = emptyWindowContents; // parent.layout(); } } void WorkbenchWindow::HideEmptyWindowContents() { if (emptyWindowContentsCreated) { if (emptyWindowContents != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(emptyWindowContents); emptyWindowContents = 0; //this->GetPageComposite().layout(); } emptyWindowContentsCreated = false; } } WorkbenchWindow::ServiceLocatorOwner::ServiceLocatorOwner(WorkbenchWindow* wnd) : window(wnd) { } void WorkbenchWindow::ServiceLocatorOwner::Dispose() { Shell::Pointer shell = window->GetShell(); if (shell != 0) { window->Close(); } } bool WorkbenchWindow::PageList::Add(IWorkbenchPage::Pointer object) { pagesInCreationOrder.push_back(object); pagesInActivationOrder.push_front(object); // It will be moved to top only when activated. return true; } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::Begin() { return pagesInCreationOrder.begin(); } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::End() { return pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Contains(IWorkbenchPage::Pointer object) { return std::find(pagesInCreationOrder.begin(), pagesInCreationOrder.end(), object) != pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Remove(IWorkbenchPage::Pointer object) { if (active == object) { active = 0; } pagesInActivationOrder.removeAll(object); const int origSize = pagesInCreationOrder.size(); pagesInCreationOrder.removeAll(object); return origSize != pagesInCreationOrder.size(); } void WorkbenchWindow::PageList::Clear() { pagesInCreationOrder.clear(); pagesInActivationOrder.clear(); active = 0; } bool WorkbenchWindow::PageList::IsEmpty() { return pagesInCreationOrder.empty(); } -const QList& WorkbenchWindow::PageList::GetPages() +QList WorkbenchWindow::PageList::GetPages() const { return pagesInCreationOrder; } void WorkbenchWindow::PageList::SetActive(IWorkbenchPage::Pointer page) { if (active == page) { return; } active = page; if (page.IsNotNull()) { pagesInActivationOrder.removeAll(page); pagesInActivationOrder.push_back(page); } } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetActive() const { return active.Cast(); } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetNextActive() { if (active.IsNull()) { if (pagesInActivationOrder.empty()) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.back().Cast(); } if (pagesInActivationOrder.size() < 2) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.at(pagesInActivationOrder.size()-2).Cast(); } WorkbenchWindow::ShellActivationListener::ShellActivationListener(WorkbenchWindow::Pointer w) : window(w) { } void WorkbenchWindow::ShellActivationListener::ShellActivated(const ShellEvent::Pointer& /*event*/) { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = true; wnd->serviceLocator->Activate(); wnd->GetWorkbenchImpl()->SetActivatedWindow(wnd); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellActivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellActivated(); } wnd->GetWorkbenchImpl()->FireWindowActivated(wnd); } //liftRestrictions(); } void WorkbenchWindow::ShellActivationListener::ShellDeactivated(const ShellEvent::Pointer& /*event*/) { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = false; //imposeRestrictions(); wnd->serviceLocator->Deactivate(); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } wnd->GetWorkbenchImpl()->FireWindowDeactivated(wnd); } } void WorkbenchWindow::TrackShellActivation(Shell::Pointer shell) { shellActivationListener.reset(new ShellActivationListener(WorkbenchWindow::Pointer(this))); shell->AddShellListener(shellActivationListener.data()); } WorkbenchWindow::ControlResizeListener::ControlResizeListener(WorkbenchWindow* w) : window(w) { } GuiTk::IControlListener::Events::Types WorkbenchWindow::ControlResizeListener::GetEventTypes() const { return Events::MOVED | Events::RESIZED; } void WorkbenchWindow:: ControlResizeListener::ControlMoved(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow:: ControlResizeListener::ControlResized(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow::ControlResizeListener::SaveBounds() { WorkbenchWindow::Pointer wnd(window); Shell::Pointer shell = wnd->GetShell(); if (shell == 0) { return; } // if (shell->IsDisposed()) // { // return; // } if (shell->GetMinimized()) { return; } if (shell->GetMaximized()) { wnd->asMaximizedState = true; return; } wnd->asMaximizedState = false; wnd->normalBounds = shell->GetBounds(); } void WorkbenchWindow::TrackShellResize(Shell::Pointer newShell) { controlResizeListener = new ControlResizeListener(this); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(newShell->GetControl(), controlResizeListener); } bool WorkbenchWindow::UpdatesDeferred() const { return largeUpdates > 0; } void WorkbenchWindow::InitializeDefaultServices() { workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WINDOW_SCOPE, GetWorkbench(), this, NULL, 1)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); //ActionCommandMappingService* mappingService = new ActionCommandMappingService(); //serviceLocator->RegisterService(IActionCommandMappingService, mappingService); } QSet > WorkbenchWindow::GetMenuRestrictions() const { return QSet >(); } void WorkbenchWindow::FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue) { PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue)); genericPropertyListeners.propertyChange(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h index 6815e57d29..171df8b4ae 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h @@ -1,738 +1,738 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHWINDOW_H_ #define BERRYWORKBENCHWINDOW_H_ #include "berryIWorkbenchWindow.h" #include "berryIPerspectiveListener.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryWindow.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryShellPool.h" #include "berryServiceLocator.h" #include "berryWWinPartService.h" #include "application/berryWorkbenchAdvisor.h" #include "application/berryWorkbenchWindowAdvisor.h" #include "application/berryActionBarAdvisor.h" -#include +#include namespace berry { struct IEvaluationReference; struct IWorkbench; struct IWorkbenchPage; struct IPartService; struct ISelectionService; struct IPerspectiveDescriptor; struct IWorkbenchLocationService; class Workbench; class WorkbenchPage; class WWinActionBars; /** * \ingroup org_blueberry_ui_qt * */ class BERRY_UI_QT WorkbenchWindow: public Window, public IWorkbenchWindow { public: /** * Toolbar visibility change property. */ static const QString PROP_TOOLBAR_VISIBLE; // = "toolbarVisible"; /** * Perspective bar visibility change property. */ static const QString PROP_PERSPECTIVEBAR_VISIBLE; // = "perspectiveBarVisible"; /** * The status line visibility change property. for internal use only. */ static const QString PROP_STATUS_LINE_VISIBLE; // = "statusLineVisible"; public: berryObjectMacro(WorkbenchWindow) WorkbenchWindow(int number); ~WorkbenchWindow(); Object* GetService(const QString& key); bool HasService(const QString& key) const; int Open(); bool Close(); Shell::Pointer GetShell() const; /** * @see org.blueberry.ui.IPageService */ void AddPerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ void RemovePerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ IPerspectiveListener::Events& GetPerspectiveEvents(); /** * Returns the action bars for this window. */ WWinActionBars* GetActionBars(); SmartPointer GetActivePage() const; - SmartPointer GetPage(int i); + SmartPointer GetPage(int i) const; - void SetPerspectiveExcludeList(std::vector v); - std::vector GetPerspectiveExcludeList(); + void SetPerspectiveExcludeList(const QStringList& v); + QStringList GetPerspectiveExcludeList() const; - void SetViewExcludeList(std::vector v); - std::vector GetViewExcludeList(); + void SetViewExcludeList(const QStringList& v); + QStringList GetViewExcludeList() const; /** * Sets the active page within the window. * * @param in * identifies the new active page, or null for no * active page */ void SetActivePage(SmartPointer in); /** * Answer the menu manager for this window. */ MenuManager* GetMenuManager() const; IWorkbench* GetWorkbench(); IPartService* GetPartService(); ISelectionService* GetSelectionService(); /** * @return whether the tool bar should be shown. This is only applicable if * the window configurer also wishes the cool bar to be visible. */ bool GetToolBarVisible() const; /** * @return whether the perspective bar should be shown. This is only * applicable if the window configurer also wishes the perspective * bar to be visible. */ bool GetPerspectiveBarVisible() const; /** * @return whether the status line should be shown. This is only applicable if * the window configurer also wishes status line to be visible. */ bool GetStatusLineVisible() const; /** * Add a generic property listener. * * @param listener the listener to add */ void AddPropertyChangeListener(IPropertyChangeListener* listener); /** * Removes a generic property listener. * * @param listener the listener to remove */ void RemovePropertyChangeListener(IPropertyChangeListener* listener); SmartPointer OpenPage(const QString& perspectiveId, IAdaptable* input); SmartPointer OpenPage(IAdaptable* input); //TODO menu manager //virtual void* GetMenuManager() = 0; virtual bool SaveState(IMemento::Pointer memento); /** * Called when this window is about to be closed. * * Subclasses may overide to add code that returns false to * prevent closing under certain conditions. */ virtual bool OkToClose(); bool RestoreState(IMemento::Pointer memento, SmartPointer< IPerspectiveDescriptor> activeDescriptor); /** * Returns the number. This corresponds to a page number in a window or a * window number in the workbench. */ int GetNumber(); /** * update the action bars. */ void UpdateActionBars(); /** *

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

*

* Important: always use with largeUpdateEnd! *

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

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

*

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

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

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

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

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

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

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

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

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

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

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

*/ /* private - DO NOT CHANGE */ ActionBarAdvisor::Pointer GetActionBarAdvisor(); /* * Returns the IWorkbench implementation. */ Workbench* GetWorkbenchImpl(); bool UnableToRestorePage(IMemento::Pointer pageMem); /** * Close the window. * * Assumes that busy cursor is active. */ bool BusyClose(); /** * Unconditionally close this window. Assumes the proper flags have been set * correctly (e.i. closing and updateDisabled) */ bool HardClose(); /** * Close all of the pages. */ void CloseAllPages(); /** * Save all of the pages. Returns true if the operation succeeded. */ bool SaveAllPages(bool bConfirm); void ShowEmptyWindowContents(); void HideEmptyWindowContents(); struct ShellActivationListener: public IShellListener { ShellActivationListener(WorkbenchWindow::Pointer window); void ShellActivated(const ShellEvent::Pointer& event); void ShellDeactivated(const ShellEvent::Pointer& event); private: WorkbenchWindow::WeakPtr window; }; QScopedPointer shellActivationListener; /** * Hooks a listener to track the activation and deactivation of the window's * shell. Notifies the active part and editor of the change */ void TrackShellActivation(Shell::Pointer shell); struct ControlResizeListener: public GuiTk::IControlListener { ControlResizeListener(WorkbenchWindow* window); GuiTk::IControlListener::Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer e); void ControlResized(GuiTk::ControlEvent::Pointer e); private: void SaveBounds(); WorkbenchWindow* window; }; GuiTk::IControlListener::Pointer controlResizeListener; /** * Hooks a listener to track the resize of the window's shell. Stores the * new bounds if in normal state - that is, not in minimized or maximized * state) */ void TrackShellResize(Shell::Pointer newShell); /** * Returns true iff we are currently deferring UI processing due to a large * update * * @return true iff we are deferring UI updates. */ bool UpdatesDeferred() const; /** * Initializes all of the default command-based services for the workbench * window. */ void InitializeDefaultServices(); void FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue); }; } #endif /*BERRYWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.cpp index d217761e89..2ac1ed66f6 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.cpp @@ -1,205 +1,195 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryUITestApplication.h" #include #include -#include +#include +#include #include #include "internal/berryUITestWorkbenchAdvisor.h" namespace berry { class WorkbenchCloseRunnable: public Poco::Runnable { public: WorkbenchCloseRunnable(IWorkbench* workbench) : workbench(workbench) { } void run() { workbench->Close(); } private: IWorkbench* workbench; }; UITestApplication::TestRunnable::TestRunnable(UITestApplication* app, - const std::string& testPlugin) : + const QString& testPlugin) : app(app), testPlugin(testPlugin) { } void UITestApplication::TestRunnable::run() { try { app->testDriverResult = BlueBerryTestDriver::Run(testPlugin, true); - } catch (Poco::IOException& e) + } + catch (const ctkException& e) + { + qWarning() << e.printStackTrace(); + } + catch (const std::exception& e) { - std::cerr << e.displayText() << std::endl; - //TODO print stack trace - //Debug::PrintStackTrace(); + qWarning() << e.what(); } } UITestApplication::UITestApplication() { } -UITestApplication::UITestApplication(const UITestApplication& other) -{ - Q_UNUSED(other) - throw std::logic_error("Copy constructor not implemented"); -} - int UITestApplication::Start() { // Get the plug-in to test try { - testPlugin = Platform::GetConfiguration().getString( - Platform::ARG_TESTPLUGIN); + testPlugin = QString::fromStdString(Platform::GetConfiguration().getString( + Platform::ARG_TESTPLUGIN.toStdString())); } catch (const Poco::NotFoundException& /*e*/) { BERRY_ERROR << "You must specify a test plug-in id via " << Platform::ARG_TESTPLUGIN << "="; return 1; } // Get the application to test IApplication* application = GetApplication(); poco_assert(application); int result = RunApplication(application); if (IApplication::EXIT_OK != result) { std::cerr << "UITestRunner: Unexpected result from running application " << application << ": " << result << std::endl; } return testDriverResult; } void UITestApplication::Stop() { IWorkbench* workbench = PlatformUI::GetWorkbench(); if (!workbench) return; Display* display = workbench->GetDisplay(); WorkbenchCloseRunnable runnable(workbench); display->SyncExec(&runnable); } void UITestApplication::RunTests() { TestRunnable runnable(this, testPlugin); testableObject->TestingStarting(); testableObject->RunTest(&runnable); testableObject->TestingFinished(); } -IApplication* UITestApplication::GetApplication() throw (CoreException) +IApplication* UITestApplication::GetApplication() { - const IExtension* extension = 0; + IExtension::Pointer extension; /*Platform::GetExtensionPointService()->GetExtension( Starter::XP_APPLICATIONS, GetApplicationToRun());*/ - IConfigurationElement::vector extensions( - Platform::GetExtensionPointService()->GetConfigurationElementsFor(Starter::XP_APPLICATIONS)); - IConfigurationElement::vector::iterator iter; + QList extensions( + Platform::GetExtensionRegistry()->GetConfigurationElementsFor(Starter::XP_APPLICATIONS)); - std::string appToRun = GetApplicationToRun(); - std::string id; - for (iter = extensions.begin(); iter != extensions.end(); ++iter) + QString appToRun = GetApplicationToRun(); + QString id; + foreach (const IConfigurationElement::Pointer& configElem, extensions) + { + id = configElem->GetAttribute("id"); + if(id == appToRun) { - if((*iter)->GetAttribute("id", id)) - { - if(id == appToRun) - { - extension = (*iter)->GetDeclaringExtension(); - break; - } - } + extension = configElem->GetDeclaringExtension(); + break; } + } IApplication* app = 0; if (extension) { - std::vector elements( - extension->GetConfigurationElements()); - if (elements.size() > 0) + QList elements( + extension->GetConfigurationElements()); + if (!elements.isEmpty()) { - std::vector runs( - elements[0]->GetChildren("run")); - if (runs.size() > 0) + QList runs( + elements[0]->GetChildren("run")); + if (!runs.isEmpty()) { - app = runs[0]->CreateExecutableExtension ("class"); //$NON-NLS-1$ - if (app == 0) - { - // support legacy BlueBerry extensions - app = runs[0]->CreateExecutableExtension ("class", IApplication::GetManifestName()); - } + app = runs[0]->CreateExecutableExtension ("class"); } } return app; } return this; } -std::string UITestApplication::GetApplicationToRun() +QString UITestApplication::GetApplicationToRun() { - std::string testApp; + QString testApp; try { - testApp = Platform::GetConfiguration().getString( - Platform::ARG_TESTAPPLICATION); + testApp = QString::fromStdString(Platform::GetConfiguration().getString( + Platform::ARG_TESTAPPLICATION.toStdString())); } - catch (Poco::NotFoundException) + catch (const Poco::NotFoundException&) { } return testApp; } int UITestApplication::RunApplication(IApplication* application) { testableObject = PlatformUI::GetTestableObject(); testableObject->SetTestHarness(ITestHarness::Pointer(this)); if (application == dynamic_cast(this)) return RunUITestWorkbench(); return application->Start(); } int UITestApplication::RunUITestWorkbench() { Display* display = PlatformUI::CreateDisplay(); UITestWorkbenchAdvisor advisor; return PlatformUI::CreateAndRunWorkbench(display, &advisor); } } diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.h b/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.h index d97df16a0d..2493c9f40d 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.h +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/berryUITestApplication.h @@ -1,86 +1,85 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYUITESTAPPLICATION_H_ #define BERRYUITESTAPPLICATION_H_ #include #include #include #include #include namespace berry { class BERRY_UITEST_EXPORT UITestApplication: public QObject, public IApplication, public ITestHarness { Q_OBJECT Q_INTERFACES(berry::IApplication berry::ITestHarness) public: UITestApplication(); - UITestApplication(const UITestApplication& other); int Start(); void Stop(); /* * @see berry#ITestHarness#RunTests() */ void RunTests(); private: TestableObject::Pointer testableObject; int testDriverResult; - std::string testPlugin; + QString testPlugin; /* * return the application to run, or null if not even the default application * is found. */ - IApplication* GetApplication() throw (CoreException); + IApplication* GetApplication(); /** * The -BlueBerry.testApplication argument specifies the application to be run. * If the argument is not set, an empty string is returned and the UITestApplication * itself will be started. */ - std::string GetApplicationToRun(); + QString GetApplicationToRun(); int RunApplication(IApplication* application); int RunUITestWorkbench(); struct TestRunnable: public Poco::Runnable { - TestRunnable(UITestApplication* app, const std::string& testPlugin); + TestRunnable(UITestApplication* app, const QString& testPlugin); void run(); private: UITestApplication* app; - std::string testPlugin; + QString testPlugin; }; }; } #endif /* BERRYUITESTAPPLICATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp index 4c1ea4558c..19d4df9803 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp @@ -1,268 +1,268 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryUITestCase.h" #include #include #include "util/berryEmptyPerspective.h" #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include #endif namespace berry { IAdaptable* UITestCase::GetPageInput() { return 0; } -UITestCase::UITestCase(const std::string& testName) : +UITestCase::UITestCase(const QString& testName) : TestCase(testName) { // ErrorDialog.NO_UI = true; fWorkbench = PlatformUI::GetWorkbench(); } -void UITestCase::failexc(const std::string& message, const std::exception& e, - long lineNumber, const std::string& fileName) +void UITestCase::failexc(const QString& message, const std::exception& e, + long /*lineNumber*/, const QString& /*fileName*/) { //TODO IStatus // If the exception is a CoreException with a multistatus // then print out the multistatus so we can see all the info. // if (e instanceof CoreException) { // IStatus status = ((CoreException) e).getStatus(); // write(status, 0); // } else // e.printStackTrace(); - CPPUNIT_FAIL(message + ": " + e.what()); + CPPUNIT_FAIL(message.toStdString() + ": " + e.what()); } IWorkbenchWindow::Pointer UITestCase::OpenTestWindow() { return OpenTestWindow(EmptyPerspective::PERSP_ID); } IWorkbenchWindow::Pointer UITestCase::OpenTestWindow( - const std::string& perspectiveId) + const QString& perspectiveId) { try { IWorkbenchWindow::Pointer window = fWorkbench->OpenWorkbenchWindow( perspectiveId, GetPageInput()); WaitOnShell(window->GetShell()); return window; - } catch (WorkbenchException& e) + } catch (const WorkbenchException& e) { - CPPUNIT_FAIL(e.displayText()); + CPPUNIT_FAIL(e.what()); return IWorkbenchWindow::Pointer(0); } } void UITestCase::CloseAllTestWindows() { - std::list::iterator i = testWindows.begin(); while (!testWindows.empty()) { testWindows.back()->Close(); testWindows.pop_back(); } } -IWorkbenchPage::Pointer UITestCase::OpenTestPage(IWorkbenchWindow::Pointer /*win*/) +IWorkbenchPage::Pointer UITestCase::OpenTestPage(const IWorkbenchWindow::Pointer& /*win*/) { // IWorkbenchPage[] pages = openTestPage(win, 1); // if (pages != null) // return pages[0]; // else return IWorkbenchPage::Pointer(0); } -std::vector UITestCase::OpenTestPage( - IWorkbenchWindow::Pointer /*win*/, int /*pageTotal*/) +QList UITestCase::OpenTestPage( + const IWorkbenchWindow::Pointer& /*win*/, int /*pageTotal*/) { // try { // IWorkbenchPage[] pages = new IWorkbenchPage[pageTotal]; // IAdaptable input = getPageInput(); // // for (int i = 0; i < pageTotal; i++) { // pages[i] = win.openPage(EmptyPerspective.PERSP_ID, input); // } // return pages; // } catch (WorkbenchException e) { // fail(); // return null; // } - return std::vector(); + return QList(); } -void UITestCase::CloseAllPages(IWorkbenchWindow::Pointer /*window*/) +void UITestCase::CloseAllPages(const IWorkbenchWindow::Pointer& /*window*/) { // IWorkbenchPage[] pages = window.getPages(); // for (int i = 0; i < pages.length; i++) // pages[i].close(); } -void UITestCase::Trace(const std::string& msg) +void UITestCase::Trace(const QString& msg) { - std::cerr << msg << std::endl; + qDebug() << msg; } void UITestCase::setUp() { - Trace("----- " + this->getName()); - Trace(this->getName() + ": setUp..."); + QString name = QString::fromStdString(this->getName()); + Trace("----- " + name); + Trace(name + ": setUp..."); AddWindowListener(); berry::TestCase::setUp(); } void UITestCase::DoSetUp() { // do nothing. } void UITestCase::tearDown() { - Trace(this->getName() + ": tearDown...\n"); + Trace(QString::fromStdString(this->getName()) + ": tearDown...\n"); RemoveWindowListener(); berry::TestCase::tearDown(); } void UITestCase::DoTearDown() { ProcessEvents(); CloseAllTestWindows(); ProcessEvents(); } void UITestCase::ProcessEvents() { // Display display = PlatformUI.getWorkbench().getDisplay(); // if (display != null) // while (display.readAndDispatch()) // ; } void UITestCase::ManageWindows(bool manage) { windowListener->SetEnabled(manage); } IWorkbench* UITestCase::GetWorkbench() { return fWorkbench; } -UITestCase::TestWindowListener::TestWindowListener(std::list< - IWorkbenchWindow::Pointer>& testWindows) : - enabled(true), testWindows(testWindows) +UITestCase::TestWindowListener::TestWindowListener( + QList& testWindows) + : enabled(true), testWindows(testWindows) { } void UITestCase::TestWindowListener::SetEnabled(bool enabled) { this->enabled = enabled; } void UITestCase::TestWindowListener::WindowActivated( - IWorkbenchWindow::Pointer /*window*/) + const IWorkbenchWindow::Pointer& /*window*/) { // do nothing } void UITestCase::TestWindowListener::WindowDeactivated( - IWorkbenchWindow::Pointer /*window*/) + const IWorkbenchWindow::Pointer& /*window*/) { // do nothing } void UITestCase::TestWindowListener::WindowClosed( - IWorkbenchWindow::Pointer window) + const IWorkbenchWindow::Pointer& window) { if (enabled) - testWindows.remove(window); + testWindows.removeAll(window); } void UITestCase::TestWindowListener::WindowOpened( - IWorkbenchWindow::Pointer window) + const IWorkbenchWindow::Pointer& window) { if (enabled) testWindows.push_back(window); } void UITestCase::Indent(std::ostream& output, unsigned int indent) { for (unsigned int i = 0; i < indent; i++) output << " "; } // void UITestCase::Write(IStatus status, unsigned int indent) { // PrintStream output = System.out; // indent(output, indent); // output.println("Severity: " + status.getSeverity()); // // indent(output, indent); // output.println("Plugin ID: " + status.getPlugin()); // // indent(output, indent); // output.println("Code: " + status.getCode()); // // indent(output, indent); // output.println("Message: " + status.getMessage()); // // if (status.getException() != null) { // indent(output, indent); // output.print("Exception: "); // status.getException().printStackTrace(output); // } // // if (status.isMultiStatus()) { // IStatus[] children = status.getChildren(); // for (int i = 0; i < children.length; i++) // write(children[i], indent + 1); // } // } void UITestCase::AddWindowListener() { - windowListener = new TestWindowListener(testWindows); - fWorkbench->AddWindowListener(windowListener); + windowListener.reset(new TestWindowListener(testWindows)); + fWorkbench->AddWindowListener(windowListener.data()); } void UITestCase::RemoveWindowListener() { if (windowListener) { - fWorkbench->RemoveWindowListener(windowListener); + fWorkbench->RemoveWindowListener(windowListener.data()); } } void UITestCase::WaitOnShell(Shell::Pointer /*shell*/) { ProcessEvents(); // long endTime = System.currentTimeMillis() + 5000; // // while (shell.getDisplay().getActiveShell() != shell // && System.currentTimeMillis() < endTime) { // processEvents(); // } } } diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h index 23f17b23b0..ea0030f974 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h @@ -1,212 +1,212 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYUITESTCASE_H_ #define BERRYUITESTCASE_H_ #include #include #include #include #include #include namespace berry { /** * UITestCase is a useful super class for most * UI tests cases. It contains methods to create new windows * and pages. It will also automatically close the test * windows when the tearDown method is called. */ class BERRY_UITEST_EXPORT UITestCase: public TestCase { public: /** * Returns the workbench page input to use for newly created windows. * * @return the page input to use for newly created windows * @since 3.1 */ static IAdaptable* GetPageInput(); - UITestCase(const std::string& testName); + UITestCase(const QString& testName); /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * The default implementation does nothing. * Subclasses may extend. */ virtual void DoSetUp(); /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * The default implementation closes all test windows, processing events both before * and after doing so. * Subclasses may extend. */ virtual void DoTearDown(); /** * Fails the test due to the given throwable. */ - void failexc(const std::string& message, const std::exception& e, + void failexc(const QString& message, const std::exception& e, long lineNumber = -1, - const std::string& fileName = "unknown"); + const QString& fileName = "unknown"); /** * Open a test window with the empty perspective. */ IWorkbenchWindow::Pointer OpenTestWindow(); /** * Open a test window with the provided perspective. */ - IWorkbenchWindow::Pointer OpenTestWindow(const std::string& perspectiveId); + IWorkbenchWindow::Pointer OpenTestWindow(const QString& perspectiveId); /** * Close all test windows. */ void CloseAllTestWindows(); /** * Open a test page with the empty perspective in a window. */ - IWorkbenchPage::Pointer OpenTestPage(IWorkbenchWindow::Pointer win); + IWorkbenchPage::Pointer OpenTestPage(const IWorkbenchWindow::Pointer& win); /** * Open "n" test pages with the empty perspective in a window. */ - std::vector OpenTestPage( - IWorkbenchWindow::Pointer win, int pageTotal); + QList OpenTestPage( + const IWorkbenchWindow::Pointer& win, int pageTotal); /** * Close all pages within a window. */ - void CloseAllPages(IWorkbenchWindow::Pointer window); + void CloseAllPages(const IWorkbenchWindow::Pointer& window); protected: /** * Outputs a trace message to the trace output device, if enabled. * By default, trace messages are sent to System.out. * * @param msg the trace message */ - void Trace(const std::string& msg); + void Trace(const QString& msg); /** * Simple implementation of setUp. Subclasses are prevented * from overriding this method to maintain logging consistency. * DoSetUp() should be overriden instead. */ void setUp(); /** * Simple implementation of tearDown. Subclasses are prevented * from overriding this method to maintain logging consistency. * DoTearDown() should be overriden instead. */ void tearDown(); static void ProcessEvents(); /** * Set whether the window listener will manage opening and closing of created windows. */ void ManageWindows(bool manage); /** * Returns the workbench. * * @return the workbench * @since 3.1 */ IWorkbench* GetWorkbench(); class TestWindowListener: public IWindowListener { private: bool enabled; - std::list& testWindows; + QList& testWindows; public: - berryObjectMacro(TestWindowListener); + berryObjectMacro(TestWindowListener) - TestWindowListener(std::list& testWindows); + TestWindowListener(QList& testWindows); void SetEnabled(bool enabled); - void WindowActivated(IWorkbenchWindow::Pointer window); + void WindowActivated(const IWorkbenchWindow::Pointer& window); - void WindowDeactivated(IWorkbenchWindow::Pointer window); + void WindowDeactivated(const IWorkbenchWindow::Pointer& window); - void WindowClosed(IWorkbenchWindow::Pointer window); + void WindowClosed(const IWorkbenchWindow::Pointer& window); - void WindowOpened(IWorkbenchWindow::Pointer window); + void WindowOpened(const IWorkbenchWindow::Pointer& window); }; IWorkbench* fWorkbench; private: - std::list testWindows; + QList testWindows; - TestWindowListener::Pointer windowListener; + QScopedPointer windowListener; static void Indent(std::ostream& output, unsigned int indent); //static void Write(IStatus status, unsigned int indent); /** * Adds a window listener to the workbench to keep track of * opened test windows. */ void AddWindowListener(); /** * Removes the listener added by addWindowListener. */ void RemoveWindowListener(); /** * Try and process events until the new shell is the active shell. This may * never happen, so time out after a suitable period. * * @param shell * the shell to wait on * @since 3.2 */ void WaitOnShell(Shell::Pointer shell); }; #define failuimsg(msg, exc) \ (this->failexc(msg, exc, __LINE__, __FILE__)) } #endif /* BERRYUITESTCASE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp index b3dc1bdbdf..747826b9ab 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp @@ -1,39 +1,39 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryUITestWorkbenchAdvisor.h" #include "berryUITestWorkbenchWindowAdvisor.h" namespace berry { UITestWorkbenchAdvisor::UITestWorkbenchAdvisor() { } WorkbenchWindowAdvisor* UITestWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer::Pointer configurer) { return new UITestWorkbenchWindowAdvisor(configurer); } -std::string UITestWorkbenchAdvisor::GetInitialWindowPerspectiveId() +QString UITestWorkbenchAdvisor::GetInitialWindowPerspectiveId() { - return ""; + return QString::null; } } diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h index 028f102a29..25f67997e7 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h @@ -1,41 +1,41 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYUITESTWORKBENCHADVISOR_H_ #define BERRYUITESTWORKBENCHADVISOR_H_ #include namespace berry { class UITestWorkbenchAdvisor : public WorkbenchAdvisor { public: UITestWorkbenchAdvisor(); WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer::Pointer configurer); - std::string GetInitialWindowPerspectiveId(); + QString GetInitialWindowPerspectiveId(); }; } #endif /* BERRYUITESTWORKBENCHADVISOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp index 67d93c7bff..c39ec2c9de 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp @@ -1,54 +1,55 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryEmptyPerspective.h" namespace berry { -std::string EmptyPerspective::LastPerspective; -const std::string EmptyPerspective::PERSP_ID = +QString EmptyPerspective::LastPerspective; +const QString EmptyPerspective::PERSP_ID = "org.blueberry.uitest.util.EmptyPerspective"; -const std::string EmptyPerspective::PERSP_ID2 = +const QString EmptyPerspective::PERSP_ID2 = "org.blueberry.uitest.util.EmptyPerspective2"; EmptyPerspective::EmptyPerspective() { } EmptyPerspective::EmptyPerspective(const EmptyPerspective& other) + : QObject() { Q_UNUSED(other) } -std::string EmptyPerspective::GetLastPerspective() +QString EmptyPerspective::GetLastPerspective() { return LastPerspective; } -void EmptyPerspective::SetLastPerspective(const std::string& perspId) +void EmptyPerspective::SetLastPerspective(const QString& perspId) { LastPerspective = perspId; } void EmptyPerspective::CreateInitialLayout(IPageLayout::Pointer layout) { SetLastPerspective(layout->GetDescriptor()->GetId()); // do no layout, this is the empty perspective } } diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.h b/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.h index d66f2c2dad..6325dae8c9 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.h +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/util/berryEmptyPerspective.h @@ -1,93 +1,93 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEMPTYPERSPECTIVE_H_ #define BERRYEMPTYPERSPECTIVE_H_ #include #include namespace berry { /** * This perspective is used for testing api. It defines an initial * layout with no parts, just an editor area. */ class BERRY_UITEST_EXPORT EmptyPerspective: public QObject, public IPerspectiveFactory { Q_OBJECT Q_INTERFACES(berry::IPerspectiveFactory) private: - static std::string LastPerspective; + static QString LastPerspective; public: EmptyPerspective(const EmptyPerspective& other); /** * The perspective id for the empty perspective. */ - static const std::string PERSP_ID; // = "org.blueberry.uitest.util.EmptyPerspective"; + static const QString PERSP_ID; // = "org.blueberry.uitest.util.EmptyPerspective"; /** * The perspective id for the second empty perspective. */ - static const std::string PERSP_ID2; // = "org.blueberry.uitest.util.EmptyPerspective2"; + static const QString PERSP_ID2; // = "org.blueberry.uitest.util.EmptyPerspective2"; /** * Returns the descriptor for the perspective last opened using this factory. * * @return the descriptor for the perspective last opened using this factory, or null */ - static std::string GetLastPerspective(); + static QString GetLastPerspective(); /** * Sets the descriptor for the perspective last opened using this factory. * * @param persp the descriptor for the perspective last opened using this factory, or null */ - static void SetLastPerspective(const std::string& perspId); + static void SetLastPerspective(const QString& perspId); /** * Constructs a new Default layout engine. */ EmptyPerspective(); /** * Defines the initial layout for a perspective. * * Implementors of this method may add additional views to a * perspective. The perspective already contains an editor folder * with ID = ILayoutFactory::ID_EDITORS. Add additional views * to the perspective in reference to the editor folder. * * This method is only called when a new perspective is created. If * an old perspective is restored from a persistence file then * this method is not called. * * @param factory the factory used to add views to the perspective */ void CreateInitialLayout(IPageLayout::Pointer layout); }; } #endif /* BERRYEMPTYPERSPECTIVE_H_ */ diff --git a/BlueBerry/Documentation/snippets/org.blueberry.ui.qt.help-config/main.cpp b/BlueBerry/Documentation/snippets/org.blueberry.ui.qt.help-config/main.cpp index 135666acba..8b22983ca3 100644 --- a/BlueBerry/Documentation/snippets/org.blueberry.ui.qt.help-config/main.cpp +++ b/BlueBerry/Documentation/snippets/org.blueberry.ui.qt.help-config/main.cpp @@ -1,130 +1,130 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include class MyApplicationPlugin : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: MyApplicationPlugin(); ~MyApplicationPlugin(); //! [0] void start(ctkPluginContext* context) { // Get a service reference for the Config Admin service ctkServiceReference cmRef = context->getServiceReference(); ctkConfigurationAdmin* configAdmin = 0; if (cmRef) { configAdmin = context->getService(cmRef); } // Use the CTK Configuration Admin service to configure the BlueBerry help system. // This assumes that the plug-in providing the Config Admin implementation is // already active. if (configAdmin) { // Get a ctkConfiguration object for the PID "org.blueberry.services.help" // (or create an unbound instance if it does not exist yet). ctkConfigurationPtr conf = configAdmin->getConfiguration("org.blueberry.services.help", QString()); // Configure the help system using a custom home page ctkDictionary helpProps; helpProps.insert("homePage", "qthelp://org.company.plugin/bundle/index.html"); conf->update(helpProps); // Unget the service context->ungetService(cmRef); } else { // Warn that the Config Admin service is unavailable } } //! [0] void stop(ctkPluginContext *context); //! [1] void requestHelp(ctkPluginContext* context) { if (context == 0) { // Warn that the plugin context is zero return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help" && p->getState() != ctkPlugin::ACTIVE) { // The plug-in is in RESOLVED state but is not started yet. // Try to activate the plug-in explicitly, so that it can react // to events send via the CTK Event Admin. try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException&) { // Warn that activating the org.blueberry.ui.qt.help plug-in failed return; } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { // Warn that the ctkEventAdmin service was not found } else { // Create the event and send it asynchronuously ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } //! [1] private: }; -int main(int argc, char* argv[]) +int main(int /*argc*/, char* /*argv*/[]) { return 0; } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/DicomView.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/DicomView.cpp index 6f32ccfa6f..ac5d50b87a 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/DicomView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer.views/src/internal/DicomView.cpp @@ -1,105 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "DicomView.h" #include "org_mitk_example_gui_customviewer_views_Activator.h" #include "mitkIDataStorageService.h" #include "mitkDicomSeriesReader.h" #include "mitkImage.h" #include #include #include #include "QDockWidget" const std::string DicomView::VIEW_ID = "org.mitk.customviewer.views.dicomview"; DicomView::DicomView() : m_Parent(0) { } DicomView::~DicomView() { } // //! [DicomViewCreatePartControl] void DicomView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Parent = parent; m_Controls.setupUi(parent); //remove unused widgets QPushButton* downloadButton = parent->findChild("downloadButton"); downloadButton->setVisible(false); connect(m_Controls.importButton, SIGNAL(clicked()), m_Controls.widget, SLOT(OnFolderCDImport())); connect(m_Controls.widget, SIGNAL(SignalDicomToDataManager(const QHash&)), this, SLOT(AddDataNodeFromDICOM(const QHash&))); m_Parent->setEnabled(true); } // //! [DicomViewCreatePartControl] // //! [DicomViewCreateAddDataNodeInformation] void DicomView::AddDataNodeFromDICOM( QHash eventProperties) { QStringList listOfFilesForSeries; mitk::DicomSeriesReader::StringContainer seriesToLoad; listOfFilesForSeries = eventProperties["FilesForSeries"].toStringList(); if (!listOfFilesForSeries.isEmpty()){ QStringListIterator it(listOfFilesForSeries); while (it.hasNext()) { seriesToLoad.push_back(it.next().toStdString()); } mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad); if (node.IsNull()) { MITK_ERROR << "Error loading Dicom series"; } // //! [DicomViewCreateAddDataNodeLoadSeries] else { // //! [DicomViewCreateAddDataNode] mitk::DataStorage::Pointer ds = this->GetDataStorage(); ds->Add(node); // //! [DicomViewCreateAddDataNode] mitk::RenderingManager::GetInstance()->SetDataStorage(ds); mitk::TimeGeometry::Pointer geometry = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geometry); // //! [DicomViewCreateAddDataNodeActivatePersp] berry::IWorkbenchWindow::Pointer window = this->GetSite()->GetWorkbenchWindow(); - std::string perspectiveId = "org.mitk.example.viewerperspective"; + QString perspectiveId = "org.mitk.example.viewerperspective"; window->GetWorkbench()->ShowPerspective(perspectiveId, berry::IWorkbenchWindow::Pointer(window)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // //! [DicomViewCreateAddDataNodeActivatePersp] } } } void DicomView::SetFocus () { } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp index 876001b044..fb3857a8e7 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp @@ -1,59 +1,59 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CustomViewerWorkbenchAdvisor.h" #include "CustomViewerWorkbenchWindowAdvisor.h" #include "berryIQtStyleManager.h" #include "org_mitk_example_gui_customviewer_Activator.h" -const std::string CustomViewerWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.viewerperspective"; +const QString CustomViewerWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.viewerperspective"; // //! [WorkbenchAdvisorCreateWindowAdvisor] berry::WorkbenchWindowAdvisor* CustomViewerWorkbenchAdvisor::CreateWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) { wwAdvisor.reset(new CustomViewerWorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } // //! [WorkbenchAdvisorCreateWindowAdvisor] CustomViewerWorkbenchAdvisor::~CustomViewerWorkbenchAdvisor() { } // //! [WorkbenchAdvisorInit] void CustomViewerWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); ctkPluginContext* pluginContext = org_mitk_example_gui_customviewer_Activator::GetPluginContext(); ctkServiceReference serviceReference = pluginContext->getServiceReference(); //always granted by org.blueberry.ui.qt Q_ASSERT(serviceReference); berry::IQtStyleManager* styleManager = pluginContext->getService(serviceReference); Q_ASSERT(styleManager); QString styleName = "CustomStyle"; styleManager->AddStyle(":/customstyle.qss", styleName); styleManager->SetStyle(":/customstyle.qss"); //styleManager->AddStyle("/home/me/customstyle.qss", styleName); //styleManager->SetStyle("/home/me/customstyle.qss"); } // //! [WorkbenchAdvisorInit] -std::string CustomViewerWorkbenchAdvisor::GetInitialWindowPerspectiveId() +QString CustomViewerWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h index e39d8796a8..86837c2c55 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h @@ -1,55 +1,55 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include /** * \brief A WorkbenchAdvisor class for the custom viewer plug-in. * * This WorkbenchAdvisor class for the custom viewer plug-in adds and sets a Qt-Stylesheet * file to the berry::QtStyleManager during the initialization phase for customization purpose. */ // //! [WorkbenchAdvisorDecl] class CustomViewerWorkbenchAdvisor : public berry::QtWorkbenchAdvisor // //! [WorkbenchAdvisorDecl] { public: /** * Holds the ID-String of the initial window perspective. */ - static const std::string DEFAULT_PERSPECTIVE_ID; + static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer); ~CustomViewerWorkbenchAdvisor(); /** * Gets the style manager (berry::IQtStyleManager), adds and initializes a Qt-Stylesheet-File (.qss). */ void Initialize(berry::IWorkbenchConfigurer::Pointer); /** * Returns the ID-String of the initial window perspective. */ - std::string GetInitialWindowPerspectiveId(); + QString GetInitialWindowPerspectiveId(); private: QScopedPointer wwAdvisor; }; diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.cpp index c6aa944a97..8ca98fef0e 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.cpp @@ -1,165 +1,165 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CustomViewerWorkbenchWindowAdvisor.h" #include "org_mitk_example_gui_customviewer_Activator.h" #include "QtPerspectiveSwitcherTabBar.h" #include #include #include #include #include #include #include #include #include #include CustomViewerWorkbenchWindowAdvisor::CustomViewerWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) { } CustomViewerWorkbenchWindowAdvisor::~CustomViewerWorkbenchWindowAdvisor() { } void CustomViewerWorkbenchWindowAdvisor::PostWindowCreate() { //for stylesheet customization //static_cast(this->GetWindowConfigurer()->GetWindow()->GetShell()->GetControl())->dumpObjectTree(); } // //! [CustomViewerWorkbenchWindowAdvisorPreWindowOpen] void CustomViewerWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = this->GetWindowConfigurer(); configurer->SetTitle("Spartan Viewer"); configurer->SetShowMenuBar(false); - configurer->SetShowCoolBar(false); + configurer->SetShowToolBar(false); configurer->SetShowPerspectiveBar(false); configurer->SetShowStatusLine(false); } // //! [CustomViewerWorkbenchWindowAdvisorPreWindowOpen] // //! [WorkbenchWindowAdvisorCreateWindowContentsHead] void CustomViewerWorkbenchWindowAdvisor::CreateWindowContents(berry::Shell::Pointer shell) { //the all containing main window QMainWindow* mainWindow = static_cast(shell->GetControl()); // //! [WorkbenchWindowAdvisorCreateWindowContentsHead] mainWindow->setVisible(true); //the widgets QWidget* CentralWidget = new QWidget(mainWindow); CentralWidget->setObjectName("CentralWidget"); CentralWidget->setVisible(true); QtPerspectiveSwitcherTabBar* PerspectivesTabBar = new QtPerspectiveSwitcherTabBar(this->GetWindowConfigurer()->GetWindow()); PerspectivesTabBar->setObjectName("PerspectivesTabBar"); PerspectivesTabBar->addTab("Image Viewer"); PerspectivesTabBar->addTab("DICOM-Manager"); PerspectivesTabBar->setVisible(true); PerspectivesTabBar->setDrawBase(false); QPushButton* StyleUpdateButton = new QPushButton("Update Style", mainWindow); StyleUpdateButton->setMaximumWidth(100); StyleUpdateButton->setObjectName("StyleUpdateButton"); QObject::connect(StyleUpdateButton, SIGNAL( clicked() ), this, SLOT( UpdateStyle() )); QToolButton* OpenFileButton = new QToolButton(mainWindow); OpenFileButton->setMaximumWidth(100); OpenFileButton->setObjectName("FileOpenButton"); OpenFileButton->setText("Open File"); QObject::connect(OpenFileButton, SIGNAL( clicked() ), this, SLOT( OpenFile() )); QWidget* PageComposite = new QWidget(CentralWidget); PageComposite->setObjectName("PageComposite"); PageComposite->setVisible(true); //the layouts QVBoxLayout* CentralWidgetLayout = new QVBoxLayout(CentralWidget); CentralWidgetLayout->contentsMargins(); CentralWidgetLayout->setContentsMargins(9,9,9,9); CentralWidgetLayout->setSpacing(0); CentralWidgetLayout->setObjectName("CentralWidgetLayout"); QHBoxLayout* PerspectivesLayer = new QHBoxLayout(mainWindow); PerspectivesLayer->setObjectName("PerspectivesLayer"); QHBoxLayout* PageCompositeLayout = new QHBoxLayout(PageComposite); PageCompositeLayout->setContentsMargins(0,0,0,0); PageCompositeLayout->setSpacing(0); PageComposite->setLayout(PageCompositeLayout); // //! [WorkbenchWindowAdvisorCreateWindowContents] //all glued together mainWindow->setCentralWidget(CentralWidget); CentralWidgetLayout->addLayout(PerspectivesLayer); CentralWidgetLayout->addWidget(PageComposite); CentralWidget->setLayout(CentralWidgetLayout); PerspectivesLayer->addWidget(PerspectivesTabBar); PerspectivesLayer->addSpacing(300); PerspectivesLayer->addWidget(OpenFileButton); //for style customization convenience /*PerspectivesLayer->addSpacing(10); PerspectivesLayer->addWidget(StyleUpdateButton);*/ //for correct initial layout, see also bug#1654 CentralWidgetLayout->activate(); CentralWidgetLayout->update(); - this->GetWindowConfigurer()->CreatePageComposite(static_cast(PageComposite)); + this->GetWindowConfigurer()->CreatePageComposite(PageComposite); // //! [WorkbenchWindowAdvisorCreateWindowContents] } // //! [WorkbenchWindowAdvisorUpdateStyle] void CustomViewerWorkbenchWindowAdvisor::UpdateStyle() { ctkPluginContext* pluginContext = org_mitk_example_gui_customviewer_Activator::GetPluginContext(); ctkServiceReference serviceReference = pluginContext->getServiceReference(); //granted by org.blueberry.ui.qt Q_ASSERT(serviceReference); berry::IQtStyleManager* styleManager = pluginContext->getService(serviceReference); Q_ASSERT(styleManager); styleManager->SetStyle("/home/me/customstyle.qss"); } // //! [WorkbenchWindowAdvisorUpdateStyle] // //! [WorkbenchWindowAdvisorOpenFile] void CustomViewerWorkbenchWindowAdvisor::OpenFile() { // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(NULL, "Open", /*d->getLastFileOpenPath()*/ QString(), mitk::CoreObjectFactory::GetInstance()->GetFileExtensions()); if (fileNames.empty()) return; mitk::WorkbenchUtil::LoadFiles(fileNames, this->GetWindowConfigurer()->GetWindow(), false); // //! [WorkbenchWindowAdvisorOpenFile] // //! [WorkbenchWindowAdvisorOpenFilePerspActive] berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); - std::string perspectiveId = "org.mitk.example.viewerperspective"; + QString perspectiveId = "org.mitk.example.viewerperspective"; window->GetWorkbench()->ShowPerspective(perspectiveId, berry::IWorkbenchWindow::Pointer(window)); // //! [WorkbenchWindowAdvisorOpenFilePerspActive] } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.h b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.h index 4e37b53b8a..08cde1b180 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchWindowAdvisor.h @@ -1,78 +1,79 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef CUSTOMVIEWERWORKBENCHWINDOWADVISOR_H_ #define CUSTOMVIEWERWORKBENCHWINDOWADVISOR_H_ #include -#include +#include + #include /** * \brief A WorkbenchWindowAdvisor class for the custom viewer plug-in. * * This class suits the custom viewer plug-in. Menu bar, tool bar and status bar are made invisible, * and the window title for the custom viewer is being set. The workbench window is being customized, * i.e. a perspectives tab-bar is arranged according to the PageComposite. The PageComposite is then * laid out according to perspective related contents by the WindowConfigurer. * * @see{ CustomViewerWorkbenchWindowAdvisor::PreWindowOpen(), CustomViewerWorkbenchWindowAdvisor::CreateWindowContents() } */ // //! [CustomViewerWorkbenchWindowAdvisorClassDeclaration] class CustomViewerWorkbenchWindowAdvisor : public QObject, public berry::WorkbenchWindowAdvisor // //! [CustomViewerWorkbenchWindowAdvisorClassDeclaration] { Q_OBJECT public: /** * Standard constructor. */ CustomViewerWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer); /** * Standard destructor. */ ~CustomViewerWorkbenchWindowAdvisor(); /** * Customizes the workbench window, i.e. arrange a perspectives tab-bar according to the * PageComposite. The PageComposite is given to the WindowConfigurer for perspective related layout. */ void CreateWindowContents(berry::Shell::Pointer shell); /** * For arbitrary actions after the window has been created but not yet opened. */ void PostWindowCreate(); /** * Menu bar, tool bar and status bar are made invisible, and the window title is being set. */ void PreWindowOpen(); private Q_SLOTS: /** * Allows for runtime stylesheet update. */ void UpdateStyle(); void OpenFile(); }; #endif /*CUSTOMVIEWERWORKBENCHWINDOWADVISOR_H_*/ diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/DicomPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/DicomPerspective.cpp index e85330f849..50eecf1283 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/DicomPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/DicomPerspective.cpp @@ -1,33 +1,33 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "DicomPerspective.h" #include "berryIFolderLayout.h" DicomPerspective::DicomPerspective() { } // //! [DicomPerspCreateLayout] void DicomPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->SetEditorAreaVisible(false); layout->AddStandaloneView("org.mitk.customviewer.views.dicomview", false, berry::IPageLayout::LEFT, 1.0f, layout->GetEditorArea()); layout->GetViewLayout("org.mitk.customviewer.views.dicomview")->SetCloseable(false); layout->GetViewLayout("org.mitk.customviewer.views.dicomview")->SetMoveable(false); } // //! [DicomPerspCreateLayout] diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.cpp index 35d1c1f44b..d1ece9ad19 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.cpp @@ -1,106 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QtPerspectiveSwitcherTabBar.h" #include #include #include /** * \brief A Listener class for perspective changes. Neccessary for consistent tab activation * in QtPerspectiveSwitcherTabBar instances. */ // //! [SwitchPerspectiveListener] struct QtPerspectiveSwitcherTabBarListener : public berry::IPerspectiveListener // //! [SwitchPerspectiveListener] { /** * Constructor. */ QtPerspectiveSwitcherTabBarListener(QtPerspectiveSwitcherTabBar* switcher) : switcher(switcher) {} /** * Only listens to perspective activation events. */ Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED; } /** * Sets the corresponding perspective index within the associated QtPerspectiveSwitcherTabBar instance. */ // //! [SwitchPerspectiveListenerPerspectiveActivated] - void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer perspective) + void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& perspective) { int index = perspective->GetId() == "org.mitk.example.viewerperspective" ? 0 : 1; switcher->setCurrentIndex(index); } // //! [SwitchPerspectiveListenerPerspectiveActivated] private: /** * The associated QtPerspectiveSwitcherTabBar instance. */ QtPerspectiveSwitcherTabBar* switcher; }; QtPerspectiveSwitcherTabBar::QtPerspectiveSwitcherTabBar(berry::IWorkbenchWindow::Pointer window) : window(window) +, perspListener(new QtPerspectiveSwitcherTabBarListener(this)) { this->tabChanged = false; QWidget* parent = static_cast(window->GetShell()->GetControl()); this->setParent(parent); QObject::connect( this, SIGNAL( currentChanged( int ) ) , this, SLOT( SwitchPerspective( void ) ) ); - this->perspListener = new QtPerspectiveSwitcherTabBarListener(this); - window->AddPerspectiveListener(this->perspListener); + window->AddPerspectiveListener(this->perspListener.data()); } QtPerspectiveSwitcherTabBar::~QtPerspectiveSwitcherTabBar() { + window->RemovePerspectiveListener(this->perspListener.data()); } // //! [PerspectiveSwitcherSwitchPerspective] void QtPerspectiveSwitcherTabBar::SwitchPerspective() { if (!this->tabChanged) { this->tabChanged = true; return; } int index = this->currentIndex(); if (index == 0) { - std::string perspectiveId = "org.mitk.example.viewerperspective"; + QString perspectiveId = "org.mitk.example.viewerperspective"; this->window->GetWorkbench()->ShowPerspective(perspectiveId, berry::IWorkbenchWindow::Pointer(window)); } else if (index == 1) { - std::string perspectiveId = "org.mitk.example.dicomperspective"; + QString perspectiveId = "org.mitk.example.dicomperspective"; this->window->GetWorkbench()->ShowPerspective(perspectiveId, berry::IWorkbenchWindow::Pointer(window)); } } // //! [PerspectiveSwitcherSwitchPerspective] diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.h b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.h index 8b6ce5922f..d954e8482f 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/QtPerspectiveSwitcherTabBar.h @@ -1,78 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QTPERSPECTIVESWITCHERTABBAR_H_ #define QTPERSPECTIVESWITCHERTABBAR_H_ #include #include #include #include /** * \brief A QTabBar providing perspective bar functionality in BlueBerry applications. * * This subclass of QTabBar acts as a perspective bar in BlueBerry applications. Providing * perspective switching functionality in a tab-bar like outfit, this class serves as an * alternative to the ToolBar based berry::QtPerspectiveSwitcher class. */ // //! [PerspectiveSwitcherDeclaration] class QtPerspectiveSwitcherTabBar : public QTabBar // //! [PerspectiveSwitcherDeclaration] { Q_OBJECT public: /** * Constructor. */ QtPerspectiveSwitcherTabBar(berry::IWorkbenchWindow::Pointer window); /** * Standard destructor. */ ~QtPerspectiveSwitcherTabBar(); private Q_SLOTS: /** * Implements perspective switching. */ void SwitchPerspective(); private: berry::IWorkbenchWindow::Pointer window; - berry::IPerspectiveListener::Pointer perspListener; + QScopedPointer perspListener; QHash perspIdToActionMap; /** * Neccessary to prevent initial tab switching. */ bool tabChanged; /** * Listener for perspective changes. Neccessary for consistent tab activation. */ friend struct QtPerspectiveSwitcherTabBarListener; }; #endif /* QTPERSPECTIVESWITCHERTABBAR_H_ */ diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/ViewerPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/ViewerPerspective.cpp index 08a964b735..daa0a7c857 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/ViewerPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/ViewerPerspective.cpp @@ -1,32 +1,32 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ViewerPerspective.h" #include "berryIFolderLayout.h" ViewerPerspective::ViewerPerspective() { } // //! [AddView1] void ViewerPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->SetEditorAreaVisible(false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, layout->GetEditorArea()); layout->AddStandaloneView("org.mitk.customviewer.views.simplerenderwindowview", false, berry::IPageLayout::RIGHT, 0.7f, layout->GetEditorArea()); } // //! [AddView1] diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/IChangeText.h b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/IChangeText.h index d1e6bc8661..434293a4f8 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/IChangeText.h +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/IChangeText.h @@ -1,37 +1,37 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef ICHANGETEXT_H_ #define ICHANGETEXT_H_ #include #include "org_mitk_example_gui_extensionpointdefinition_Export.h" struct org_mitk_example_gui_extensionpointdefinition_EXPORT IChangeText : public virtual berry::Object { - berryInterfaceMacro(IChangeText, ::) + berryObjectMacro(IChangeText) virtual ~IChangeText(); virtual QString ChangeText(const QString& s) = 0; }; Q_DECLARE_INTERFACE(IChangeText, "org.mitk.example.IChangeText") #endif /*ICHANGETEXT_H_*/ diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextDescriptor.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextDescriptor.cpp index 71435827fe..09ea5b796c 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextDescriptor.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextDescriptor.cpp @@ -1,86 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ChangeTextDescriptor.h" #include "ExtensionPointDefinitionConstants.h" -#include "berryPlatformException.h" +#include "berryIContributor.h" ChangeTextDescriptor::ChangeTextDescriptor(berry::IConfigurationElement::Pointer changeTextExtensionPoint) : m_ChangeTextExtensionPoint(changeTextExtensionPoint) { - std::string id; - std::string name; + this->m_Id = this->m_ChangeTextExtensionPoint->GetAttribute(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_ID); + this->m_Name = this->m_ChangeTextExtensionPoint->GetAttribute(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_NAME); // Check if the "id" and "name" attributes are available - if (!this->m_ChangeTextExtensionPoint->GetAttribute(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_ID, id) || - !this->m_ChangeTextExtensionPoint->GetAttribute(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_NAME, name)) + if (this->m_Id.isNull() || this->m_Name.isNull()) { - throw berry::CoreException("Invalid changetext configuration element (missing id or name) from: " + - m_ChangeTextExtensionPoint->GetContributor()); + throw ctkRuntimeException("Invalid changetext configuration element (missing id or name) from: " + + m_ChangeTextExtensionPoint->GetContributor()->GetName()); } - this->m_Id = QString::fromStdString(id); - this->m_Name = QString::fromStdString(name); - // Get the optional "description" child element - std::vector descriptions( + QList descriptions( this->m_ChangeTextExtensionPoint->GetChildren(ExtensionPointDefinitionConstants::CHANGETEXT_CHILD_DESCRIPTION)); - if(!descriptions.empty()) + if(!descriptions.isEmpty()) { - this->m_Description = QString::fromStdString(descriptions[0]->GetValue()); + this->m_Description = descriptions[0]->GetValue(); } } ChangeTextDescriptor::~ChangeTextDescriptor() { } IChangeText::Pointer ChangeTextDescriptor::CreateChangeText() { if(this->m_ChangeText == 0) { // "class" refers to xml attribute in a xml tag this->m_ChangeText = this->m_ChangeTextExtensionPoint ->CreateExecutableExtension(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_CLASS); } return this->m_ChangeText; } QString ChangeTextDescriptor::GetID() const { return this->m_Id; } QString ChangeTextDescriptor::GetDescription() const { return this->m_Description; } QString ChangeTextDescriptor::GetName() const { return this->m_Name; } bool ChangeTextDescriptor::operator==(const Object* object) const { if (const ChangeTextDescriptor* other = dynamic_cast(object)) { return this->GetID() == other->GetID(); } return false; } diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextRegistry.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextRegistry.cpp index d2bfe8835d..64c9ff4824 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextRegistry.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ChangeTextRegistry.cpp @@ -1,58 +1,57 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include -#include +#include #include #include "ChangeTextRegistry.h" #include "ExtensionPointDefinitionConstants.h" ChangeTextRegistry::ChangeTextRegistry() { //initialize the registry by copying all available extension points into a local variable - berry::IExtensionPointService::Pointer extensionPointService = berry::Platform::GetExtensionPointService(); - std::vector allExtensionsChangeTexts - = extensionPointService->GetConfigurationElementsFor(ExtensionPointDefinitionConstants::CHANGETEXT_XP_NAME); + berry::IExtensionRegistry* extensionRegistry = berry::Platform::GetExtensionRegistry(); + QList allExtensionsChangeTexts + = extensionRegistry->GetConfigurationElementsFor(ExtensionPointDefinitionConstants::CHANGETEXT_XP_NAME); - for(std::vector::const_iterator it = allExtensionsChangeTexts.begin(); - it != allExtensionsChangeTexts.end();++it) + foreach(const berry::IConfigurationElement::Pointer& it, allExtensionsChangeTexts) { - ChangeTextDescriptor::Pointer temp(new ChangeTextDescriptor(*it)); - - if(!this->m_ListRegisteredTexts.contains(temp->GetID())) + QString id = it->GetAttribute(ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_ID); + if(id.isEmpty() || this->m_ListRegisteredTexts.contains(id)) { - m_ListRegisteredTexts.insert(temp->GetID(),temp); + BERRY_WARN << "The ChangeText ID: " << id << " is already registered."; } else { - BERRY_WARN << "The ChangeText ID: " << qPrintable(temp->GetID()) << " is already registered."; + ChangeTextDescriptor::Pointer tmp(new ChangeTextDescriptor(it)); + m_ListRegisteredTexts.insert(id, tmp); } } } ChangeTextRegistry::~ChangeTextRegistry() { } ChangeTextDescriptor::Pointer ChangeTextRegistry::Find(const QString &id) const { return this->m_ListRegisteredTexts.value(id); } QList ChangeTextRegistry::GetChangeTexts() const { return m_ListRegisteredTexts.values(); } diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp index 54d67ed0eb..9737734db4 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp @@ -1,81 +1,81 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ExtensionPointDefinition.h" // berry Includes #include #include class MinimalWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string DEFAULT_PERSPECTIVE_ID; + static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(berry::Point(600,400)); // Set an individual title configurer->SetTitle("Extension Points"); // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(false); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } - std::string GetInitialWindowPerspectiveId() + QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; -const std::string MinimalWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; +const QString MinimalWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; ExtensionPointDefinition::ExtensionPointDefinition() { } ExtensionPointDefinition::~ExtensionPointDefinition() { } int ExtensionPointDefinition::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MinimalWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void ExtensionPointDefinition::Stop() { //nothing to do } diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.cpp index 2800bb9896..7ef763cf68 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.cpp @@ -1,25 +1,25 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ExtensionPointDefinitionConstants.h" #include "ChangeTextRegistry.h" -const std::string ExtensionPointDefinitionConstants::CHANGETEXT_XP_NAME = "org.mitk.example.extensionpointdefinition.changetext"; -const std::string ExtensionPointDefinitionConstants::CHANGETEXT_CHILD_DESCRIPTION = "description"; -const std::string ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_CLASS = "class"; -const std::string ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_NAME = "name"; -const std::string ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_ID = "id"; +const QString ExtensionPointDefinitionConstants::CHANGETEXT_XP_NAME = "org.mitk.example.extensionpointdefinition.changetext"; +const QString ExtensionPointDefinitionConstants::CHANGETEXT_CHILD_DESCRIPTION = "description"; +const QString ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_CLASS = "class"; +const QString ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_NAME = "name"; +const QString ExtensionPointDefinitionConstants::CHANGETEXT_XMLATTRIBUTE_ID = "id"; diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.h b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.h index 29ec307f27..0492355173 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.h +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinitionConstants.h @@ -1,42 +1,42 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef EXTENSIONPOINTDEFINITIONCONSTANTS_H_ #define EXTENSIONPOINTDEFINITIONCONSTANTS_H_ -#include +#include /** * The ExtensionPointDefinitionConstants contains a list of unique ids in the * following form:
* "org.mitk.mybundle.mytype.propername"
* * This ids have the purpose of connecting the plugin.xml of each bundle to the * appropriate classes. * * Additionally it includes names of tags, which are used in XML files
* regarding the BlueBerry example. */ struct ExtensionPointDefinitionConstants { - static const std::string CHANGETEXT_XP_NAME; - static const std::string CHANGETEXT_CHILD_DESCRIPTION; - static const std::string CHANGETEXT_XMLATTRIBUTE_CLASS; - static const std::string CHANGETEXT_XMLATTRIBUTE_NAME; - static const std::string CHANGETEXT_XMLATTRIBUTE_ID; + static const QString CHANGETEXT_XP_NAME; + static const QString CHANGETEXT_CHILD_DESCRIPTION; + static const QString CHANGETEXT_XMLATTRIBUTE_CLASS; + static const QString CHANGETEXT_XMLATTRIBUTE_NAME; + static const QString CHANGETEXT_XMLATTRIBUTE_ID; }; #endif /*EXTENSIONPOINTDEFINITIONCONSTANTS_H_*/ diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp index d0b37b3ddf..5a2c7d8931 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/MinimalPerspective.cpp @@ -1,34 +1,34 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MinimalPerspective.h" /// Berry #include "berryIViewLayout.h" MinimalPerspective::MinimalPerspective() { } void MinimalPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free. - std::string editorAreaId = layout->GetEditorArea(); + QString editorAreaId = layout->GetEditorArea(); // Hides the editor area. layout->SetEditorAreaVisible(false); layout->AddView("org.mitk.views.minimalview", berry::IPageLayout::LEFT,0.5f, editorAreaId); -} \ No newline at end of file +} diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp index 069de09f00..e5da3b8980 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp @@ -1,162 +1,162 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkIsoSurface.h" //MITK headers #include #include #include //Qmitk headers #include #include //Qt-GUI headers #include #include #include QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/) : m_Controls(NULL), m_MitkImage(NULL), m_SurfaceCounter(0) { } void QmitkIsoSurface::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkIsoSurfaceControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_ImageSelector->SetDataStorage(this->GetDataStorage()); m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) - m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0"))); + m_Controls->thresholdLineEdit->setText(prefs->Get("defaultThreshold", "0")); } } void QmitkIsoSurface::SetFocus() { m_Controls->m_ImageSelector->setFocus(); } void QmitkIsoSurface::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_ImageSelector, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(ImageSelected(const mitk::DataNode*)) ); connect( m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface()) ); } } void QmitkIsoSurface::ImageSelected(const mitk::DataNode* item) { // nothing selected (NULL selection) if( item == 0 || item->GetData() == 0 ) return; m_MitkImage = dynamic_cast (item->GetData()); } void QmitkIsoSurface::CreateSurface() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); if(m_MitkImage != NULL) { //Value Gauss //float gsDev = 1.5; //Value for DecimatePro float targetReduction = 0.05; //ImageToSurface Instance mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode(); mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout<<"NULL Pointer for ManualSegmentationToSurfaceFilter"<SetInput( m_MitkImage ); filter->SetGaussianStandardDeviation( 0.5 ); filter->SetUseGaussianImageSmooth( true ); filter->SetThreshold( getThreshold()); //if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetTargetReduction( targetReduction ); int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys(); if(numOfPolys>2000000) { QApplication::restoreOverrideCursor(); if(QMessageBox::question(NULL, "CAUTION!!!", "The number of polygons is greater than 2 000 000. If you continue, the program might crash. How do you want to go on?", "Proceed anyway!", "Cancel immediately! (maybe you want to insert an other threshold)!",QString::null,0 ,1)==1) { return; } QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New(); surfaceNode->SetData( filter->GetOutput() ); int layer = 0; ++m_SurfaceCounter; std::ostringstream buffer; buffer << m_SurfaceCounter; std::string surfaceNodeName = "Surface " + buffer.str(); node->GetIntProperty("layer", layer); surfaceNode->SetIntProperty("layer", layer+1); surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true)); surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName)); this->GetDataStorage()->Add(surfaceNode, node); //to show surfaceContur surfaceNode->SetColor( m_RainbowColor.GetNextColor() ); surfaceNode->SetVisibility(true); mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if (renderPart) { renderPart->RequestUpdate(); } } QApplication::restoreOverrideCursor(); } float QmitkIsoSurface::getThreshold() { return m_Controls->thresholdLineEdit->text().toFloat(); } QmitkIsoSurface::~QmitkIsoSurface() { berry::IPreferences::Pointer prefs = this->GetPreferences(); if(prefs.IsNotNull()) - prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString()); + prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text()); } diff --git a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/ExtendedPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/ExtendedPerspective.cpp index b12b5f2c2b..148a7ca691 100644 --- a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/ExtendedPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/ExtendedPerspective.cpp @@ -1,37 +1,37 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ExtendedPerspective.h" // berry includes #include "berryIViewLayout.h" ExtendedPerspective::ExtendedPerspective() { } void ExtendedPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free - std::string editorAreaId = layout->GetEditorArea(); + QString editorAreaId = layout->GetEditorArea(); // Hide editor area layout->SetEditorAreaVisible(false); // add emptyviews to perspective layout->AddView("org.mitk.views.emptyview1", berry::IPageLayout::LEFT, 1.0f, editorAreaId); layout->AddView("org.mitk.views.emptyview2", berry::IPageLayout::RIGHT, 0.3f, "org.mitk.views.emptyview1"); } diff --git a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MinimalPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MinimalPerspective.cpp index a521fab2ca..8ad85214c5 100644 --- a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MinimalPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MinimalPerspective.cpp @@ -1,44 +1,44 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MinimalPerspective.h" // berry includes #include "berryIViewLayout.h" MinimalPerspective::MinimalPerspective() { } void MinimalPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free. - std::string editorAreaId = layout->GetEditorArea(); + QString editorAreaId = layout->GetEditorArea(); //! [Visibility of editor area] // set editor area to visible layout->SetEditorAreaVisible(true); //! [Visibility of editor area] // create folder with alignment "left" berry::IFolderLayout::Pointer left = layout->CreateFolder("left", berry::IPageLayout::LEFT, 0.5f, editorAreaId); // add emptyview1 to the folder left->AddView("org.mitk.views.emptyview1"); // add emptyview2 to the folder left->AddView("org.mitk.views.emptyview2"); } diff --git a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp index 4d059f27ab..682f20ddc0 100644 --- a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp +++ b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp @@ -1,86 +1,86 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MultiplePerspectives.h" // berry includes #include #include class MultiplePerspectivesWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string DEFAULT_PERSPECTIVE_ID; + static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { //! [initial window size] // Set an individual initial size configurer->SetInitialSize(berry::Point(600,400)); //! [initial window size] // Set an individual title configurer->SetTitle("Multiple Perspectives"); //! [Visibility of perspective bar] // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(true); //! [Visibility of perspective bar] wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } - std::string GetInitialWindowPerspectiveId() + QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; -const std::string MultiplePerspectivesWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; +const QString MultiplePerspectivesWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; MultiplePerspectives::MultiplePerspectives() { } MultiplePerspectives::~MultiplePerspectives() { } int MultiplePerspectives::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MultiplePerspectivesWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void MultiplePerspectives::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/ExtendedPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/ExtendedPerspective.cpp index f13f0f3bba..4626df1795 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/ExtendedPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/ExtendedPerspective.cpp @@ -1,37 +1,37 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ExtendedPerspective.h" // berry includes #include "berryIViewLayout.h" ExtendedPerspective::ExtendedPerspective() { } void ExtendedPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free. - std::string editorAreaId = layout->GetEditorArea(); + QString editorAreaId = layout->GetEditorArea(); // Hides the editor area. layout->SetEditorAreaVisible(false); // add the selection view (for providing selection events for the listener view) to the perspective layout->AddView("org.mitk.views.selectionviewmitk", berry::IPageLayout::LEFT,1.0f, editorAreaId); // add the listener view (listening for selection events of the selection view) to the perspective layout->AddView("org.mitk.views.listenerviewmitk", berry::IPageLayout::RIGHT,0.5f, "org.mitk.views.selectionviewmitk"); } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp index fb8785949e..9b95cb22b8 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp @@ -1,78 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "SelectionServiceMitk.h" // berry includes #include #include class SelectionServiceMITKWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string DEFAULT_PERSPECTIVE_ID; + static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(berry::Point(600,400)); // Set the window title configurer->SetTitle("MITK Selection Service"); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } - std::string GetInitialWindowPerspectiveId() + QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; -const std::string SelectionServiceMITKWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; +const QString SelectionServiceMITKWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceMitk::SelectionServiceMitk() { } SelectionServiceMitk::~SelectionServiceMitk() { } int SelectionServiceMitk::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceMITKWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceMitk::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ExtendedPerspective.cpp b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ExtendedPerspective.cpp index 0c01fda1ed..a4b49db454 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ExtendedPerspective.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ExtendedPerspective.cpp @@ -1,33 +1,33 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ExtendedPerspective.h" // berry includes #include "berryIViewLayout.h" void ExtendedPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { // Editors are placed for free. - std::string editorAreaId = layout->GetEditorArea(); + QString editorAreaId = layout->GetEditorArea(); // Hides the editor area. layout->SetEditorAreaVisible(false); // add the selection view (for providing selection events for the listener view) to the perspective layout->AddView("org.mitk.views.selectionview", berry::IPageLayout::LEFT,0.5f, editorAreaId); // add the listener view (listening for selection events of the selection view) to the perspective layout->AddView("org.mitk.views.listenerview", berry::IPageLayout::RIGHT,0.5f, editorAreaId); } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.cpp b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.cpp index ace54c4d99..4978ec0dc8 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.cpp @@ -1,95 +1,95 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "ListenerView.h" // berry includes #include #include #include // Qt includes #include #include #include const std::string ListenerView::VIEW_ID = "org.mitk.views.listenerview"; ListenerView::ListenerView() : m_SelectionListener(new berry::SelectionChangedAdapter(this, &ListenerView::SelectionChanged)) , m_Parent(0) { } ListenerView::~ListenerView() { // remove selection service berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - s->RemoveSelectionListener(m_SelectionListener); + s->RemoveSelectionListener(m_SelectionListener.data()); } void ListenerView::CreateQtPartControl(QWidget *parent) { // create GUI widgets m_Parent = parent; m_Controls.setupUi(parent); // register selection listener - GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener); + GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data()); m_Parent->setEnabled(true); } void ListenerView::ToggleRadioMethod(QString selectStr) { // change the radio button state according to the name of the selected element if (selectStr == "Selection 1") m_Controls.radioButton->toggle(); else if (selectStr == "Selection 2") m_Controls.radioButton_2->toggle(); } void ListenerView::SetFocus() { } //! [Qt Selection Listener method implementation] -void ListenerView::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, - berry::ISelection::ConstPointer selection) +void ListenerView::SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, + const berry::ISelection::ConstPointer& selection) { // check for null selection if (selection.IsNull()) { return; } // exclude own selection events and check whether this kind of selection can be handled if (sourcepart != this && selection.Cast()) { berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast(); // iterate over the selections (for the BlueBerry example this is always 1 for (berry::IStructuredSelection::iterator itr = currentSelection->Begin(); itr != currentSelection->End(); ++itr) { if (berry::QModelIndexObject::Pointer object = itr->Cast()) { // get name of selected ListWidgetElement QVariant text = object->GetQModelIndex().data(); // pass name of element to method for radio button state checking ToggleRadioMethod(text.toString()); } } } } //! [Qt Selection Listener method implementation] diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.h b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.h index 8dcb2d0554..f184d39a4d 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.h +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/ListenerView.h @@ -1,90 +1,90 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef LISTENERVIEW_H_ #define LISTENERVIEW_H_ // berry includes #include #include #include // ui includes #include "ui_ListenerViewControls.h" /** * \ingroup org_mitk_example_gui_selectionserviceqt * * \brief This BlueBerry view is part of the BlueBerry example * "Selection service QT". It creates two radio buttons that listen * for selection events of the Qlistwidget (SelectionProvider) and * change the radio button state accordingly. * * @see SelectionView */ class ListenerView : public berry::QtViewPart { Q_OBJECT public: static const std::string VIEW_ID; ListenerView(); ~ListenerView(); protected: void CreateQtPartControl(QWidget *parent); void SetFocus(); private Q_SLOTS: /** * @brief Simple slot function that changes the selection of the radio buttons according to the passed string. * @param selectStr QString that contains the name of the slected list element */ void ToggleRadioMethod(QString selectStr); private: //! [Qt Selection Listener method and pointer] /** * @brief Method of berry::ISelectionListener that implements the selection listener functionality. * @param sourcepart The workbench part responsible for the selection change. * @param selection This parameter holds the current selection. * * @see ISelectionListener */ - void SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, - berry::ISelection::ConstPointer selection); + void SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, + const berry::ISelection::ConstPointer& selection); /** @brief this pointer holds the selection listener */ - berry::ISelectionListener::Pointer m_SelectionListener; + QScopedPointer m_SelectionListener; //! [Qt Selection Listener method and pointer] friend struct berry::SelectionChangedAdapter; Ui::ListenerViewControls m_Controls; QWidget* m_Parent; }; #endif /*LISTENERVIEW_H_*/ diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp index 9657bfbeb6..d8b9a85f8d 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp @@ -1,78 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "SelectionServiceQt.h" // berry includes #include #include class SelectionServiceQtWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string DEFAULT_PERSPECTIVE_ID; + static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(berry::Point(600,400)); // Set the window title configurer->SetTitle("Qt Selection Service"); wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); return wwAdvisor.data(); } - std::string GetInitialWindowPerspectiveId() + QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } private: QScopedPointer wwAdvisor; }; -const std::string SelectionServiceQtWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; +const QString SelectionServiceQtWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceQt::SelectionServiceQt() { } SelectionServiceQt::~SelectionServiceQt() { } int SelectionServiceQt::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceQtWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceQt::Stop() { } diff --git a/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.cpp b/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.cpp index dd4ff8a322..bda50666ae 100644 --- a/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.cpp +++ b/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.cpp @@ -1,85 +1,85 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNavigationDataSetWriterCSV.h" #include void mitk::NavigationDataSetWriterCSV::Write (std::string path, mitk::NavigationDataSet::Pointer data) { MITK_INFO << "Writing navigation data set to file: " << path; std::ofstream stream; stream.open (path.c_str(), std::ios_base::trunc); // Pass to Stream Handler Write(&stream, data); stream.close(); } void mitk::NavigationDataSetWriterCSV::Write (std::ostream* stream, mitk::NavigationDataSet::Pointer data) { //save old locale char * oldLocale; oldLocale = setlocale( LC_ALL, 0 ); //define own locale std::locale C("C"); setlocale( LC_ALL, "C" ); //write header - int numberOfTools = data->GetNumberOfTools(); + unsigned int numberOfTools = data->GetNumberOfTools(); for (unsigned int index = 0; index < numberOfTools; index++){ *stream << "TimeStamp_Tool" << index << ";Valid_Tool" << index << ";X_Tool" << index << ";Y_Tool" << index << ";Z_Tool" << index << ";QX_Tool" << index << ";QY_Tool" << index << ";QZ_Tool" << index << ";QR_Tool" << index << ";";} *stream << "\n"; stream->precision(15); // rounding precision because we don't want to loose data. //write data MITK_INFO << "Number of timesteps: " << data->Size(); - for (int i=0; iSize(); i++) + for (unsigned int i=0; iSize(); i++) { std::vector< mitk::NavigationData::Pointer > NavigationDatasOfCurrentStep = data->GetTimeStep(i); - for (int toolIndex = 0; toolIndex < numberOfTools; toolIndex++) + for (unsigned int toolIndex = 0; toolIndex < numberOfTools; toolIndex++) { mitk::NavigationData::Pointer nd = NavigationDatasOfCurrentStep.at(toolIndex); *stream << nd->GetTimeStamp() << ";" << nd->IsDataValid() << ";" << nd->GetPosition()[0] << ";" << nd->GetPosition()[1] << ";" << nd->GetPosition()[2] << ";" << nd->GetOrientation()[0] << ";" << nd->GetOrientation()[1] << ";" << nd->GetOrientation()[2] << ";" << nd->GetOrientation()[3] << ";"; } *stream << "\n"; } //switch back to old locale setlocale( LC_ALL, oldLocale ); } mitk::NavigationDataSetWriterCSV::NavigationDataSetWriterCSV() {} mitk::NavigationDataSetWriterCSV::~NavigationDataSetWriterCSV() {} diff --git a/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.h b/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.h index 07f6a29356..bf51ddd5f9 100644 --- a/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.h +++ b/Modules/IGT/IO/mitkNavigationDataSetWriterCSV.h @@ -1,35 +1,35 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_ #define MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_ #include namespace mitk { class MITKIGT_EXPORT NavigationDataSetWriterCSV { public: - NavigationDataSetWriterCSV(); - ~NavigationDataSetWriterCSV(); + NavigationDataSetWriterCSV(); + virtual~NavigationDataSetWriterCSV(); virtual void Write (std::string path, mitk::NavigationDataSet::Pointer ); virtual void Write (std::ostream* stream, mitk::NavigationDataSet::Pointer); }; } #endif // MITKNavigationDataSetWriterCSV_H_HEADER_INCLUDED_ diff --git a/Modules/IGT/IO/mitkNavigationDataSetWriterXML.cpp b/Modules/IGT/IO/mitkNavigationDataSetWriterXML.cpp index eb6d8d7c9a..ba3f96159a 100644 --- a/Modules/IGT/IO/mitkNavigationDataSetWriterXML.cpp +++ b/Modules/IGT/IO/mitkNavigationDataSetWriterXML.cpp @@ -1,137 +1,137 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // MITK #include "mitkNavigationDataSetWriterXML.h" // Third Party #include #include #include #include mitk::NavigationDataSetWriterXML::NavigationDataSetWriterXML() { } mitk::NavigationDataSetWriterXML::~NavigationDataSetWriterXML() { } void mitk::NavigationDataSetWriterXML::Write (std::string path, mitk::NavigationDataSet::Pointer data) { std::ofstream stream; stream.open (path.c_str(), std::ios_base::trunc); // Pass to Stream Handler Write(&stream, data); stream.close(); } void mitk::NavigationDataSetWriterXML::Write (std::ostream* stream, mitk::NavigationDataSet::Pointer data) { //save old locale char * oldLocale; oldLocale = setlocale( LC_ALL, 0 ); StreamHeader(stream, data); StreamData(stream, data); StreamFooter(stream); // Cleanup stream->flush(); //switch back to old locale setlocale( LC_ALL, oldLocale ); } void mitk::NavigationDataSetWriterXML::StreamHeader (std::ostream* stream, mitk::NavigationDataSet::Pointer data) { stream->precision(10); //TODO store date and GMT time //checking if the stream is good if (stream->good()) { *stream << "" << std::endl; /**m_Stream << "" << std::endl;*/ // should be a generic version, meaning a member variable, which has the actual version *stream << " " << "GetNumberOfTools() << "\" version=\"1.0\">" << std::endl; } } void mitk::NavigationDataSetWriterXML::StreamData (std::ostream* stream, mitk::NavigationDataSet::Pointer data) { // For each time step in the Dataset for (mitk::NavigationDataSet::NavigationDataSetIterator it = data->Begin(); it != data->End(); it++) { - for (int toolIndex = 0; toolIndex < it->size(); toolIndex++) + for (std::size_t toolIndex = 0; toolIndex < it->size(); toolIndex++) { mitk::NavigationData::Pointer nd = it->at(toolIndex); TiXmlElement* elem = new TiXmlElement("ND"); elem->SetDoubleAttribute("Time", nd->GetIGTTimeStamp()); // elem->SetAttribute("SystemTime", sysTimeStr); // tag for system time elem->SetDoubleAttribute("Tool", toolIndex); elem->SetDoubleAttribute("X", nd->GetPosition()[0]); elem->SetDoubleAttribute("Y", nd->GetPosition()[1]); elem->SetDoubleAttribute("Z", nd->GetPosition()[2]); elem->SetDoubleAttribute("QX", nd->GetOrientation()[0]); elem->SetDoubleAttribute("QY", nd->GetOrientation()[1]); elem->SetDoubleAttribute("QZ", nd->GetOrientation()[2]); elem->SetDoubleAttribute("QR", nd->GetOrientation()[3]); elem->SetDoubleAttribute("C00", nd->GetCovErrorMatrix()[0][0]); elem->SetDoubleAttribute("C01", nd->GetCovErrorMatrix()[0][1]); elem->SetDoubleAttribute("C02", nd->GetCovErrorMatrix()[0][2]); elem->SetDoubleAttribute("C03", nd->GetCovErrorMatrix()[0][3]); elem->SetDoubleAttribute("C04", nd->GetCovErrorMatrix()[0][4]); elem->SetDoubleAttribute("C05", nd->GetCovErrorMatrix()[0][5]); elem->SetDoubleAttribute("C10", nd->GetCovErrorMatrix()[1][0]); elem->SetDoubleAttribute("C11", nd->GetCovErrorMatrix()[1][1]); elem->SetDoubleAttribute("C12", nd->GetCovErrorMatrix()[1][2]); elem->SetDoubleAttribute("C13", nd->GetCovErrorMatrix()[1][3]); elem->SetDoubleAttribute("C14", nd->GetCovErrorMatrix()[1][4]); elem->SetDoubleAttribute("C15", nd->GetCovErrorMatrix()[1][5]); if (nd->IsDataValid()) elem->SetAttribute("Valid",1); else elem->SetAttribute("Valid",0); if (nd->GetHasOrientation()) elem->SetAttribute("hO",1); else elem->SetAttribute("hO",0); if (nd->GetHasPosition()) elem->SetAttribute("hP",1); else elem->SetAttribute("hP",0); *stream << " " << *elem << std::endl; delete elem; } } } void mitk::NavigationDataSetWriterXML::StreamFooter (std::ostream* stream) { *stream << "" << std::endl; } diff --git a/Modules/IGT/IO/mitkNavigationDataSetWriterXML.h b/Modules/IGT/IO/mitkNavigationDataSetWriterXML.h index 1f006cd452..8d0e48b64b 100644 --- a/Modules/IGT/IO/mitkNavigationDataSetWriterXML.h +++ b/Modules/IGT/IO/mitkNavigationDataSetWriterXML.h @@ -1,41 +1,41 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKNavigationDataSetWriterXML_H_HEADER_INCLUDED_ #define MITKNavigationDataSetWriterXML_H_HEADER_INCLUDED_ #include namespace mitk { class MITKIGT_EXPORT NavigationDataSetWriterXML { public: NavigationDataSetWriterXML(); - ~NavigationDataSetWriterXML(); + virtual ~NavigationDataSetWriterXML(); virtual void Write (std::string path, mitk::NavigationDataSet::Pointer ); virtual void Write (std::ostream* stream, mitk::NavigationDataSet::Pointer); protected: virtual void StreamHeader (std::ostream* stream, mitk::NavigationDataSet::Pointer data); virtual void StreamData (std::ostream* stream, mitk::NavigationDataSet::Pointer data); virtual void StreamFooter (std::ostream* stream); }; } #endif // MITKNavigationDataSetWriterXML_H_HEADER_INCLUDED_ diff --git a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp index 84332ccbfe..a2c44b27e7 100755 --- a/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp +++ b/Plugins/org.mitk.core.ext/src/internal/mitkCoreExtActivator.cpp @@ -1,85 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCoreExtActivator.h" -#include "mitkPicFileReader.h" -#include #include "mitkCoreExtConstants.h" - +#include "mitkLogMacros.h" #include "mitkInputDeviceRegistry.h" #include #include #include #include #include namespace mitk { void CoreExtActivator::start(ctkPluginContext* context) { Q_UNUSED(context) this->StartInputDeviceModules(context); } void CoreExtActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) } - void mitk::CoreExtActivator::StartInputDeviceModules(ctkPluginContext* context) + void CoreExtActivator::StartInputDeviceModules(ctkPluginContext* context) { m_InputDeviceRegistry.reset(new InputDeviceRegistry()); context->registerService(m_InputDeviceRegistry.data()); // Gets the last setting of the preferences; if a device was selected, // it will still be activated after a restart ctkServiceReference prefServiceRef = context->getServiceReference(); if (!prefServiceRef) { MITK_WARN << "Preferences service not available"; return; } berry::IPreferencesService* prefService = context->getService(prefServiceRef); berry::IPreferences::Pointer extPreferencesNode = prefService->GetSystemPreferences()->Node(CoreExtConstants::INPUTDEVICE_PREFERENCES); // Initializes the modules QList descriptors(m_InputDeviceRegistry->GetInputDevices()); for (QList::const_iterator it = descriptors.begin(); it != descriptors.end(); ++it) { if (extPreferencesNode->GetBool((*it)->GetID(), false)) { IInputDevice::Pointer temp = (*it)->CreateInputDevice(); temp->RegisterInputDevice(); } } } CoreExtActivator::~CoreExtActivator() { } } // end namespace mitk #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_core_ext, mitk::CoreExtActivator) #endif diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp index ca41399d3f..2f5a9fc9c6 100644 --- a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp @@ -1,351 +1,352 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkWorkbenchUtil.h" +#include #include #include #include #include #include #include "mitkIDataStorageService.h" #include "mitkDataStorageEditorInput.h" #include "mitkRenderingManager.h" #include "mitkIRenderWindowPart.h" #include "mitkIRenderingManager.h" #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkCoreObjectFactory.h" #include "QmitkIOUtil.h" #include #include #include #include "internal/org_mitk_gui_common_Activator.h" namespace mitk { struct WorkbenchUtilPrivate { /** * Get the editor descriptor for a given name using the editorDescriptor * passed in as a default as a starting point. * * @param name * The name of the element to open. * @param editorReg * The editor registry to do the lookups from. * @param defaultDescriptor * IEditorDescriptor or null * @return IEditorDescriptor * @throws PartInitException * if no valid editor can be found */ static berry::IEditorDescriptor::Pointer GetEditorDescriptor(const QString& name, berry::IEditorRegistry* editorReg, berry::IEditorDescriptor::Pointer defaultDescriptor) { if (defaultDescriptor.IsNotNull()) { return defaultDescriptor; } berry::IEditorDescriptor::Pointer editorDesc = defaultDescriptor; // next check the OS for in-place editor (OLE on Win32) if (editorReg->IsSystemInPlaceEditorAvailable(name)) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID); } // next check with the OS for an external editor if (editorDesc.IsNull() && editorReg->IsSystemExternalEditorAvailable(name)) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } // if no valid editor found, bail out if (editorDesc.IsNull()) { throw berry::PartInitException("No editor found"); } return editorDesc; } }; // //! [UtilLoadFiles] void WorkbenchUtil::LoadFiles(const QStringList &fileNames, berry::IWorkbenchWindow::Pointer window, bool openEditor) // //! [UtilLoadFiles] { if (fileNames.empty()) return; mitk::IDataStorageReference::Pointer dataStorageRef; { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dataStorageRef = dss->GetDataStorage(); context->ungetService(dsRef); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); // Do the actual work of loading the data into the data storage // Turn off ASSERT #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) int lastCrtReportType = _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); #endif DataStorage::SetOfObjects::Pointer data; try { data = QmitkIOUtil::Load(fileNames, *dataStorage); } catch (const mitk::Exception& e) { MITK_INFO << e; return; } const bool dsmodified = !data->empty(); // Set ASSERT status back to previous status. #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) if (lastCrtReportType) _CrtSetReportMode( _CRT_ASSERT, lastCrtReportType ); #endif // Check if there is an open perspective. If not, open the default perspective. if (window->GetActivePage().IsNull()) { QString defaultPerspId = window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); window->GetWorkbench()->ShowPerspective(defaultPerspId, window); } bool globalReinitOnNodeAdded = true; berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); if (prefService != nullptr) { berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("org.mitk.views.datamanager"); if(prefs.IsNotNull()) { globalReinitOnNodeAdded = prefs->GetBool("Call global reinit if node is added", true); } } if (openEditor && globalReinitOnNodeAdded) { try { // Activate the editor using the same data storage or open the default editor mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageRef)); berry::IEditorPart::Pointer editor = mitk::WorkbenchUtil::OpenEditor(window->GetActivePage(), input, true); mitk::IRenderWindowPart* renderEditor = dynamic_cast(editor.GetPointer()); mitk::IRenderingManager* renderingManager = renderEditor == 0 ? 0 : renderEditor->GetRenderingManager(); if(dsmodified && renderingManager) { mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } catch (const berry::PartInitException& e) { QString msg = "An error occurred when displaying the file(s): %1"; QMessageBox::warning(QApplication::activeWindow(), "Error displaying file", msg.arg(e.message())); } } } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, berry::IEditorInput::Pointer input, const QString &editorId, bool activate) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the input return page->OpenEditor(input, editorId, activate); } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, mitk::DataStorageEditorInput::Pointer input, bool activate, bool determineContentType) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the data storage QString name = input->GetName() + ".mitk"; berry::IEditorDescriptor::Pointer editorDesc = WorkbenchUtilPrivate::GetEditorDescriptor(name, berry::PlatformUI::GetWorkbench()->GetEditorRegistry(), GetDefaultEditor(name, determineContentType)); return page->OpenEditor(input, editorDesc->GetId(), activate); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetEditorDescriptor( const QString& name, bool /*inferContentType*/) { if (name.isEmpty()) { throw std::invalid_argument("name argument must not be empty"); } // no used for now //IContentType contentType = inferContentType ? Platform // .getContentTypeManager().findContentTypeFor(name) : null; berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); return WorkbenchUtilPrivate::GetEditorDescriptor(name, editorReg, editorReg->GetDefaultEditor(name /*, contentType*/)); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetDefaultEditor(const QString& name, bool /*determineContentType*/) { // Try file specific editor. berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); try { QString editorID; // = file.getPersistentProperty(EDITOR_KEY); if (!editorID.isEmpty()) { berry::IEditorDescriptor::Pointer desc = editorReg->FindEditor(editorID); if (desc.IsNotNull()) { return desc; } } } catch (const berry::CoreException&) { // do nothing } // IContentType contentType = null; // if (determineContentType) // { // contentType = getContentType(file); // } // Try lookup with filename return editorReg->GetDefaultEditor(name); //, contentType); } bool WorkbenchUtil::SetDepartmentLogoPreference(const QString &logoResource, ctkPluginContext *context) { // The logo must be available in the local filesystem. We check if we have not already extracted the // logo from the plug-in or if this plug-ins timestamp is newer then the already extracted logo timestamp. // If one of the conditions is true, extract it and write it to the plug-in specific storage location. const QString logoFileName = logoResource.mid(logoResource.lastIndexOf('/')+1); const QString logoPath = context->getDataFile("").absoluteFilePath(); bool extractLogo = true; QFileInfo logoFileInfo(logoPath + "/" + logoFileName); if (logoFileInfo.exists()) { // The logo has been extracted previously. Check if the plugin timestamp is newer, which // means it might contain an updated logo. QString pluginLocation = QUrl(context->getPlugin()->getLocation()).toLocalFile(); if (!pluginLocation.isEmpty()) { QFileInfo pluginFileInfo(pluginLocation); if (logoFileInfo.lastModified() > pluginFileInfo.lastModified()) { extractLogo = false; } } } if (extractLogo) { // Extract the logo from the shared library and write it to disk. QFile logo(logoResource); if (logo.open(QIODevice::ReadOnly)) { QFile localLogo(logoPath + "/" + logoFileName); if (localLogo.open(QIODevice::WriteOnly)) { localLogo.write(logo.readAll()); } } } logoFileInfo.refresh(); if (logoFileInfo.exists()) { // Get the preferences service ctkServiceReference prefServiceRef = context->getServiceReference(); berry::IPreferencesService* prefService = NULL; if (prefServiceRef) { prefService = context->getService(prefServiceRef); } if (prefService) { prefService->GetSystemPreferences()->Put("DepartmentLogo", qPrintable(logoFileInfo.absoluteFilePath())); } else { BERRY_WARN << "Preferences service not available, unable to set custom logo."; return false; } } else { BERRY_WARN << "Custom logo at " << logoFileInfo.absoluteFilePath().toStdString() << " does not exist"; return false; } return true; } } // namespace mitk diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp index c496bb4c6e..0a3e7c8ff5 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.cpp @@ -1,93 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDefaultDropTargetListener.h" #include #include #include #include #include #include "internal/org_mitk_gui_qt_application_Activator.h" #include +#include #include #include class QmitkDefaultDropTargetListenerPrivate { public: berry::IPreferences::Pointer GetPreferences() const { - berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } bool GetOpenEditor() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->GetBool("OpenEditor", true); } return true; } }; QmitkDefaultDropTargetListener::QmitkDefaultDropTargetListener() : berry::IDropTargetListener(), d(new QmitkDefaultDropTargetListenerPrivate()) { } QmitkDefaultDropTargetListener::~QmitkDefaultDropTargetListener() { } berry::IDropTargetListener::Events::Types QmitkDefaultDropTargetListener::GetDropTargetEventTypes() const { return Events::DROP; } void QmitkDefaultDropTargetListener::DropEvent(QDropEvent *event) { qDebug() << event->mimeData()->formats(); qDebug() << event->mimeData()->text(); QList fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; //TODO Qt 4.7 API //fileNames2.reserve(fileNames.size()); foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), d->GetOpenEditor()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h index 96fe2b1580..5e2ec8780d 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDefaultDropTargetListener.h @@ -1,46 +1,48 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDEFAULTDROPTARGETLISTENER_H #define QMITKDEFAULTDROPTARGETLISTENER_H #include #include +#include + class QmitkDefaultDropTargetListenerPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkDefaultDropTargetListener : public berry::IDropTargetListener { public: QmitkDefaultDropTargetListener(); virtual ~QmitkDefaultDropTargetListener(); Events::Types GetDropTargetEventTypes() const; void DropEvent(QDropEvent* event); private: const QScopedPointer d; }; #endif // QMITKDEFAULTDROPTARGETLISTENER_H diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp index 474d53bfc2..6eab0b1c51 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp @@ -1,114 +1,116 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFileOpenAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include +#include + #include class QmitkFileOpenActionPrivate { public: void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileOpenAction* action ) { m_Window = window; action->setParent(static_cast(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Open..."); action->setToolTip("Open data files (images, surfaces,...)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { - berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); - if (prefService.IsNotNull()) + berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + if (prefService) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileOpenPath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->Get("LastFileOpenPath", ""); } return QString(); } void setLastFileOpenPath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileOpenPath", path); prefs->Flush(); } } bool GetOpenEditor() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->GetBool("OpenEditor", true); } return true; } berry::IWorkbenchWindow::WeakPtr m_Window; }; QmitkFileOpenAction::QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) { d->init(window, this); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileOpenAction::~QmitkFileOpenAction() { } void QmitkFileOpenAction::Run() { // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(NULL, "Open", d->getLastFileOpenPath(), QmitkIOUtil::GetFileOpenFilterString()); if (fileNames.empty()) return; d->setLastFileOpenPath(fileNames.front()); mitk::WorkbenchUtil::LoadFiles(fileNames, d->m_Window.Lock(), d->GetOpenEditor()); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp index 327fe0e790..504dff27a5 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp @@ -1,188 +1,190 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFileSaveAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include +#include #include #include #include class QmitkFileSaveActionPrivate { private: - void HandleSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, berry::ISelection::ConstPointer selection) + void HandleSelectionChanged(const berry::IWorkbenchPart::Pointer& /*part*/, + const berry::ISelection::ConstPointer& selection) { this->setEnabled(selection); } - berry::ISelectionListener::Pointer m_SelectionListener; + QScopedPointer m_SelectionListener; public: QmitkFileSaveActionPrivate() : m_SelectionListener(new berry::NullSelectionChangedAdapter( this, &QmitkFileSaveActionPrivate::HandleSelectionChanged)) { } ~QmitkFileSaveActionPrivate() { if (!m_Window.Expired()) { - m_Window.Lock()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener); + m_Window.Lock()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data()); } } void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileSaveAction* action ) { m_Window = window; m_Action = action; action->setParent(static_cast(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Save..."); action->setToolTip("Save data objects (images, surfaces,...)"); berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService(); setEnabled(selectionService->GetSelection()); - selectionService->AddSelectionListener(m_SelectionListener); + selectionService->AddSelectionListener(m_SelectionListener.data()); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { - berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); - if (prefService.IsNotNull()) + berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); + if (prefService != nullptr) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileSavePath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { - return QString::fromStdString(prefs->Get("LastFileSavePath", "")); + return prefs->Get("LastFileSavePath", ""); } return QString(); } void setLastFileSavePath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { - prefs->Put("LastFileSavePath", path.toStdString()); + prefs->Put("LastFileSavePath", path); prefs->Flush(); } } void setEnabled(berry::ISelection::ConstPointer selection) { mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast(); if (nodeSelection.IsNotNull() && !selection->IsEmpty()) { bool enable = false; std::list dataNodes = nodeSelection->GetSelectedDataNodes(); for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { if ((*nodeIter)->GetData() != NULL) { enable = true; break; } } m_Action->setEnabled(enable); } else { m_Action->setEnabled(false); } } berry::IWorkbenchWindow::WeakPtr m_Window; QAction* m_Action; }; QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileSaveAction::~QmitkFileSaveAction() { } void QmitkFileSaveAction::Run() { // Get the list of selected base data objects mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast(); if (selection.IsNull() || selection->IsEmpty()) { MITK_ERROR << "Assertion failed: data node selection is NULL or empty"; return; } std::list dataNodes = selection->GetSelectedDataNodes(); std::vector data; QStringList names; for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { data.push_back((*nodeIter)->GetData()); std::string name; (*nodeIter)->GetStringProperty("name", name); names.push_back(QString::fromStdString(name)); } try { QStringList fileNames = QmitkIOUtil::Save(data, names, d->getLastFileSavePath(), d->m_Action->parentWidget()); if (!fileNames.empty()) { d->setLastFileSavePath(QFileInfo(fileNames.back()).absolutePath()); } } catch (const mitk::Exception& e) { MITK_INFO << e; return; } } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp index 4d3c0aa5cf..6a2e403498 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp @@ -1,75 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "org_mitk_gui_qt_application_Activator.h" #include "QmitkGeneralPreferencePage.h" #include "QmitkEditorsPreferencePage.h" #include #include namespace mitk { org_mitk_gui_qt_application_Activator* org_mitk_gui_qt_application_Activator::m_Instance = 0; ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = 0; void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context) { this->m_Instance = this; this->m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context) QmitkRegisterClasses(); this->m_PrefServiceTracker.reset(new ctkServiceTracker(context)); this->m_PrefServiceTracker->open(); } void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) this->m_PrefServiceTracker.reset(); this->m_Context = 0; this->m_Instance = 0; } ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext() { return m_Context; } org_mitk_gui_qt_application_Activator *org_mitk_gui_qt_application_Activator::GetInstance() { return m_Instance; } - berry::IPreferencesService::Pointer org_mitk_gui_qt_application_Activator::GetPreferencesService() + berry::IPreferencesService* org_mitk_gui_qt_application_Activator::GetPreferencesService() { - return berry::IPreferencesService::Pointer(m_PrefServiceTracker->getService()); + return m_PrefServiceTracker->getService(); } } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_application, mitk::org_mitk_gui_qt_application_Activator) #endif diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h index 4ff5371dc5..f42cc0f9e1 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.h @@ -1,61 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H #include #include #include namespace mitk { class org_mitk_gui_qt_application_Activator : public QObject, public ctkPluginActivator { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_application") #endif Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* GetContext(); static org_mitk_gui_qt_application_Activator* GetInstance(); - berry::IPreferencesService::Pointer GetPreferencesService(); + berry::IPreferencesService* GetPreferencesService(); private: static org_mitk_gui_qt_application_Activator* m_Instance; static ctkPluginContext* m_Context; QScopedPointer > m_PrefServiceTracker; }; // org_mitk_gui_common_Activator typedef org_mitk_gui_qt_application_Activator PluginActivator; } #endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp index a9c13105ce..f20b95dbf6 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.cpp @@ -1,1355 +1,1354 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkBasicImageProcessingView.h" // QT includes (GUI) #include #include #include #include #include #include #include // Berry includes (selection service) #include #include // MITK includes (GUI) #include "QmitkStdMultiWidget.h" #include "QmitkDataNodeSelectionProvider.h" #include "mitkDataNodeObject.h" // MITK includes (general) #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateAnd.h" #include "mitkImageTimeSelector.h" #include "mitkVectorImageMapper2D.h" #include "mitkProperties.h" // Includes for image casting between ITK and MITK #include "mitkImageCast.h" #include "mitkITKImageImport.h" // ITK includes (general) #include #include // Morphological Operations #include #include #include #include #include // Smoothing #include #include #include // Threshold #include // Inversion #include // Derivatives #include #include #include // Resampling #include #include #include #include // Image Arithmetics #include #include #include #include // Boolean operations #include #include #include // Flip Image #include #include // Convenient Definitions typedef itk::Image ImageType; typedef itk::Image SegmentationImageType; typedef itk::Image FloatImageType; typedef itk::Image, 3> VectorImageType; typedef itk::BinaryBallStructuringElement BallType; typedef itk::GrayscaleDilateImageFilter DilationFilterType; typedef itk::GrayscaleErodeImageFilter ErosionFilterType; typedef itk::GrayscaleMorphologicalOpeningImageFilter OpeningFilterType; typedef itk::GrayscaleMorphologicalClosingImageFilter ClosingFilterType; typedef itk::MedianImageFilter< ImageType, ImageType > MedianFilterType; typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType> GaussianFilterType; typedef itk::TotalVariationDenoisingImageFilter TotalVariationFilterType; typedef itk::TotalVariationDenoisingImageFilter VectorTotalVariationFilterType; typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType; typedef itk::InvertIntensityImageFilter< ImageType, ImageType > InversionFilterType; typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, ImageType > GradientFilterType; typedef itk::LaplacianImageFilter< FloatImageType, FloatImageType > LaplacianFilterType; typedef itk::SobelEdgeDetectionImageFilter< FloatImageType, FloatImageType > SobelFilterType; typedef itk::ResampleImageFilter< ImageType, ImageType > ResampleImageFilterType; typedef itk::ResampleImageFilter< ImageType, ImageType > ResampleImageFilterType2; typedef itk::CastImageFilter< ImageType, FloatImageType > ImagePTypeToFloatPTypeCasterType; typedef itk::AddImageFilter< ImageType, ImageType, ImageType > AddFilterType; typedef itk::SubtractImageFilter< ImageType, ImageType, ImageType > SubtractFilterType; typedef itk::MultiplyImageFilter< ImageType, ImageType, ImageType > MultiplyFilterType; typedef itk::DivideImageFilter< ImageType, ImageType, FloatImageType > DivideFilterType; typedef itk::OrImageFilter< ImageType, ImageType > OrImageFilterType; typedef itk::AndImageFilter< ImageType, ImageType > AndImageFilterType; typedef itk::XorImageFilter< ImageType, ImageType > XorImageFilterType; typedef itk::FlipImageFilter< ImageType > FlipImageFilterType; typedef itk::LinearInterpolateImageFunction< ImageType, double > LinearInterpolatorType; typedef itk::NearestNeighborInterpolateImageFunction< ImageType, double > NearestInterpolatorType; QmitkBasicImageProcessing::QmitkBasicImageProcessing() : QmitkFunctionality(), m_Controls(NULL), m_SelectedImageNode(NULL), - m_TimeStepperAdapter(NULL), - m_SelectionListener(NULL) + m_TimeStepperAdapter(NULL) { } QmitkBasicImageProcessing::~QmitkBasicImageProcessing() { //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); //if(s) // s->RemoveSelectionListener(m_SelectionListener); } void QmitkBasicImageProcessing::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkBasicImageProcessingViewControls; m_Controls->setupUi(parent); this->CreateConnections(); //setup predictaes for combobox mitk::NodePredicateDimension::Pointer dimensionPredicate = mitk::NodePredicateDimension::New(3); mitk::NodePredicateDataType::Pointer imagePredicate = mitk::NodePredicateDataType::New("Image"); m_Controls->m_ImageSelector2->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->m_ImageSelector2->SetPredicate(mitk::NodePredicateAnd::New(dimensionPredicate, imagePredicate)); } m_Controls->gbTwoImageOps->hide(); m_SelectedImageNode = mitk::DataStorageSelection::New(this->GetDefaultDataStorage(), false); } void QmitkBasicImageProcessing::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->cbWhat1), SIGNAL( activated(int) ), this, SLOT( SelectAction(int) ) ); connect( (QObject*)(m_Controls->btnDoIt), SIGNAL(clicked()),(QObject*) this, SLOT(StartButtonClicked())); connect( (QObject*)(m_Controls->cbWhat2), SIGNAL( activated(int) ), this, SLOT( SelectAction2(int) ) ); connect( (QObject*)(m_Controls->btnDoIt2), SIGNAL(clicked()),(QObject*) this, SLOT(StartButton2Clicked())); connect( (QObject*)(m_Controls->rBOneImOp), SIGNAL( clicked() ), this, SLOT( ChangeGUI() ) ); connect( (QObject*)(m_Controls->rBTwoImOp), SIGNAL( clicked() ), this, SLOT( ChangeGUI() ) ); connect( (QObject*)(m_Controls->cbParam4), SIGNAL( activated(int) ), this, SLOT( SelectInterpolator(int) ) ); } m_TimeStepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls->sliceNavigatorTime, GetActiveStdMultiWidget()->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromBIP"); } void QmitkBasicImageProcessing::Activated() { QmitkFunctionality::Activated(); this->m_Controls->cbWhat1->clear(); this->m_Controls->cbWhat1->insertItem( NOACTIONSELECTED, "Please select operation"); this->m_Controls->cbWhat1->insertItem( CATEGORY_DENOISING, "--- Denoising ---"); this->m_Controls->cbWhat1->insertItem( GAUSSIAN, "Gaussian"); this->m_Controls->cbWhat1->insertItem( MEDIAN, "Median"); this->m_Controls->cbWhat1->insertItem( TOTALVARIATION, "Total Variation"); this->m_Controls->cbWhat1->insertItem( CATEGORY_MORPHOLOGICAL, "--- Morphological ---"); this->m_Controls->cbWhat1->insertItem( DILATION, "Dilation"); this->m_Controls->cbWhat1->insertItem( EROSION, "Erosion"); this->m_Controls->cbWhat1->insertItem( OPENING, "Opening"); this->m_Controls->cbWhat1->insertItem( CLOSING, "Closing"); this->m_Controls->cbWhat1->insertItem( CATEGORY_EDGE_DETECTION, "--- Edge Detection ---"); this->m_Controls->cbWhat1->insertItem( GRADIENT, "Gradient"); this->m_Controls->cbWhat1->insertItem( LAPLACIAN, "Laplacian (2nd Derivative)"); this->m_Controls->cbWhat1->insertItem( SOBEL, "Sobel Operator"); this->m_Controls->cbWhat1->insertItem( CATEGORY_MISC, "--- Misc ---"); this->m_Controls->cbWhat1->insertItem( THRESHOLD, "Threshold"); this->m_Controls->cbWhat1->insertItem( INVERSION, "Image Inversion"); this->m_Controls->cbWhat1->insertItem( DOWNSAMPLING, "Downsampling"); this->m_Controls->cbWhat1->insertItem( FLIPPING, "Flipping"); this->m_Controls->cbWhat1->insertItem( RESAMPLING, "Resample to"); this->m_Controls->cbWhat1->insertItem( RESCALE, "Rescale image values"); this->m_Controls->cbWhat2->clear(); this->m_Controls->cbWhat2->insertItem( TWOIMAGESNOACTIONSELECTED, "Please select on operation" ); this->m_Controls->cbWhat2->insertItem( CATEGORY_ARITHMETIC, "--- Arithmetric operations ---" ); this->m_Controls->cbWhat2->insertItem( ADD, "Add to Image 1:" ); this->m_Controls->cbWhat2->insertItem( SUBTRACT, "Subtract from Image 1:" ); this->m_Controls->cbWhat2->insertItem( MULTIPLY, "Multiply with Image 1:" ); this->m_Controls->cbWhat2->insertItem( RESAMPLE_TO, "Resample Image 1 to fit geometry:" ); this->m_Controls->cbWhat2->insertItem( DIVIDE, "Divide Image 1 by:" ); this->m_Controls->cbWhat2->insertItem( CATEGORY_BOOLEAN, "--- Boolean operations ---" ); this->m_Controls->cbWhat2->insertItem( AND, "AND" ); this->m_Controls->cbWhat2->insertItem( OR, "OR" ); this->m_Controls->cbWhat2->insertItem( XOR, "XOR" ); this->m_Controls->cbParam4->clear(); this->m_Controls->cbParam4->insertItem( LINEAR, "Linear" ); this->m_Controls->cbParam4->insertItem( NEAREST, "Nearest neighbor" ); m_Controls->dsbParam1->hide(); m_Controls->dsbParam2->hide(); m_Controls->dsbParam3->hide(); m_Controls->tlParam3->hide(); m_Controls->tlParam4->hide(); m_Controls->cbParam4->hide(); } //datamanager selection changed void QmitkBasicImageProcessing::OnSelectionChanged(std::vector nodes) { //any nodes there? if (!nodes.empty()) { // reset GUI // this->ResetOneImageOpPanel(); m_Controls->sliceNavigatorTime->setEnabled(false); m_Controls->leImage1->setText("Select an Image in Data Manager"); m_Controls->tlWhat1->setEnabled(false); m_Controls->cbWhat1->setEnabled(false); m_Controls->tlWhat2->setEnabled(false); m_Controls->cbWhat2->setEnabled(false); m_SelectedImageNode->RemoveAllNodes(); //get the selected Node mitk::DataNode* _DataNode = nodes.front(); *m_SelectedImageNode = _DataNode; //try to cast to image mitk::Image::Pointer tempImage = dynamic_cast(m_SelectedImageNode->GetNode()->GetData()); //no image if( tempImage.IsNull() || (tempImage->IsInitialized() == false) ) { m_Controls->leImage1->setText("Not an image."); return; } //2D image if( tempImage->GetDimension() < 3) { m_Controls->leImage1->setText("2D images are not supported."); return; } //image m_Controls->leImage1->setText(QString(m_SelectedImageNode->GetNode()->GetName().c_str())); // button coding if ( tempImage->GetDimension() > 3 ) { m_Controls->sliceNavigatorTime->setEnabled(true); m_Controls->tlTime->setEnabled(true); } m_Controls->tlWhat1->setEnabled(true); m_Controls->cbWhat1->setEnabled(true); m_Controls->tlWhat2->setEnabled(true); m_Controls->cbWhat2->setEnabled(true); } } void QmitkBasicImageProcessing::ChangeGUI() { if(m_Controls->rBOneImOp->isChecked()) { m_Controls->gbTwoImageOps->hide(); m_Controls->gbOneImageOps->show(); } else if(m_Controls->rBTwoImOp->isChecked()) { m_Controls->gbOneImageOps->hide(); m_Controls->gbTwoImageOps->show(); } } void QmitkBasicImageProcessing::ResetOneImageOpPanel() { m_Controls->tlParam1->setText("Param1"); m_Controls->tlParam2->setText("Param2"); m_Controls->cbWhat1->setCurrentIndex(0); m_Controls->tlTime->setEnabled(false); this->ResetParameterPanel(); m_Controls->btnDoIt->setEnabled(false); m_Controls->cbHideOrig->setEnabled(false); } void QmitkBasicImageProcessing::ResetParameterPanel() { m_Controls->tlParam->setEnabled(false); m_Controls->tlParam1->setEnabled(false); m_Controls->tlParam2->setEnabled(false); m_Controls->tlParam3->setEnabled(false); m_Controls->tlParam4->setEnabled(false); m_Controls->sbParam1->setEnabled(false); m_Controls->sbParam2->setEnabled(false); m_Controls->dsbParam1->setEnabled(false); m_Controls->dsbParam2->setEnabled(false); m_Controls->dsbParam3->setEnabled(false); m_Controls->cbParam4->setEnabled(false); m_Controls->sbParam1->setValue(0); m_Controls->sbParam2->setValue(0); m_Controls->dsbParam1->setValue(0); m_Controls->dsbParam2->setValue(0); m_Controls->dsbParam3->setValue(0); m_Controls->sbParam1->show(); m_Controls->sbParam2->show(); m_Controls->dsbParam1->hide(); m_Controls->dsbParam2->hide(); m_Controls->dsbParam3->hide(); m_Controls->cbParam4->hide(); m_Controls->tlParam3->hide(); m_Controls->tlParam4->hide(); } void QmitkBasicImageProcessing::ResetTwoImageOpPanel() { m_Controls->cbWhat2->setCurrentIndex(0); m_Controls->tlImage2->setEnabled(false); m_Controls->m_ImageSelector2->setEnabled(false); m_Controls->btnDoIt2->setEnabled(false); } void QmitkBasicImageProcessing::SelectAction(int action) { if ( ! m_SelectedImageNode->GetNode() ) return; // Prepare GUI this->ResetParameterPanel(); m_Controls->btnDoIt->setEnabled(false); m_Controls->cbHideOrig->setEnabled(false); QString text1 = "No Parameters"; QString text2 = "No Parameters"; QString text3 = "No Parameters"; QString text4 = "No Parameters"; if (action != 19) { m_Controls->dsbParam1->hide(); m_Controls->dsbParam2->hide(); m_Controls->dsbParam3->hide(); m_Controls->tlParam3->hide(); m_Controls->tlParam4->hide(); m_Controls->sbParam1->show(); m_Controls->sbParam2->show(); m_Controls->cbParam4->hide(); } // check which operation the user has selected and set parameters and GUI accordingly switch (action) { case 2: { m_SelectedAction = GAUSSIAN; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Variance:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 2 ); break; } case 3: { m_SelectedAction = MEDIAN; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 4: { m_SelectedAction = TOTALVARIATION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); m_Controls->tlParam2->setEnabled(true); m_Controls->sbParam2->setEnabled(true); text1 = "Number Iterations:"; text2 = "Regularization\n(Lambda/1000):"; m_Controls->sbParam1->setMinimum( 1 ); m_Controls->sbParam1->setMaximum( 1000 ); m_Controls->sbParam1->setValue( 40 ); m_Controls->sbParam2->setMinimum( 0 ); m_Controls->sbParam2->setMaximum( 100000 ); m_Controls->sbParam2->setValue( 1 ); break; } case 6: { m_SelectedAction = DILATION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 7: { m_SelectedAction = EROSION; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 8: { m_SelectedAction = OPENING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 9: { m_SelectedAction = CLOSING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "&Radius:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 3 ); break; } case 11: { m_SelectedAction = GRADIENT; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "Sigma of Gaussian Kernel:\n(in Image Spacing Units)"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 200 ); m_Controls->sbParam1->setValue( 2 ); break; } case 12: { m_SelectedAction = LAPLACIAN; break; } case 13: { m_SelectedAction = SOBEL; break; } case 15: { m_SelectedAction = THRESHOLD; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); m_Controls->tlParam2->setEnabled(true); m_Controls->sbParam2->setEnabled(true); text1 = "Lower threshold:"; text2 = "Upper threshold:"; m_Controls->sbParam1->setMinimum( -100000 ); m_Controls->sbParam1->setMaximum( 100000 ); m_Controls->sbParam1->setValue( 0 ); m_Controls->sbParam2->setMinimum( -100000 ); m_Controls->sbParam2->setMaximum( 100000 ); m_Controls->sbParam2->setValue( 300 ); break; } case 16: { m_SelectedAction = INVERSION; break; } case 17: { m_SelectedAction = DOWNSAMPLING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "Downsampling by Factor:"; m_Controls->sbParam1->setMinimum( 1 ); m_Controls->sbParam1->setMaximum( 100 ); m_Controls->sbParam1->setValue( 2 ); break; } case 18: { m_SelectedAction = FLIPPING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(true); text1 = "Flip across axis:"; m_Controls->sbParam1->setMinimum( 0 ); m_Controls->sbParam1->setMaximum( 2 ); m_Controls->sbParam1->setValue( 1 ); break; } case 19: { m_SelectedAction = RESAMPLING; m_Controls->tlParam1->setEnabled(true); m_Controls->sbParam1->setEnabled(false); m_Controls->sbParam1->hide(); m_Controls->dsbParam1->show(); m_Controls->dsbParam1->setEnabled(true); m_Controls->tlParam2->setEnabled(true); m_Controls->sbParam2->setEnabled(false); m_Controls->sbParam2->hide(); m_Controls->dsbParam2->show(); m_Controls->dsbParam2->setEnabled(true); m_Controls->tlParam3->show(); m_Controls->tlParam3->setEnabled(true); m_Controls->dsbParam3->show(); m_Controls->dsbParam3->setEnabled(true); m_Controls->tlParam4->show(); m_Controls->tlParam4->setEnabled(true); m_Controls->cbParam4->show(); m_Controls->cbParam4->setEnabled(true); m_Controls->dsbParam1->setMinimum(0.01); m_Controls->dsbParam1->setMaximum(10.0); m_Controls->dsbParam1->setSingleStep(0.1); m_Controls->dsbParam1->setValue(0.3); m_Controls->dsbParam2->setMinimum(0.01); m_Controls->dsbParam2->setMaximum(10.0); m_Controls->dsbParam2->setSingleStep(0.1); m_Controls->dsbParam2->setValue(0.3); m_Controls->dsbParam3->setMinimum(0.01); m_Controls->dsbParam3->setMaximum(10.0); m_Controls->dsbParam3->setSingleStep(0.1); m_Controls->dsbParam3->setValue(1.5); text1 = "x-spacing:"; text2 = "y-spacing:"; text3 = "z-spacing:"; text4 = "Interplation:"; break; } case 20: { m_SelectedAction = RESCALE; m_Controls->dsbParam1->show(); m_Controls->tlParam1->show(); m_Controls->dsbParam1->setEnabled(true); m_Controls->tlParam1->setEnabled(true); m_Controls->dsbParam2->show(); m_Controls->tlParam2->show(); m_Controls->dsbParam2->setEnabled(true); m_Controls->tlParam2->setEnabled(true); text1 = "Output minimum:"; text2 = "Output maximum:"; break; } default: return; } m_Controls->tlParam->setEnabled(true); m_Controls->tlParam1->setText(text1); m_Controls->tlParam2->setText(text2); m_Controls->tlParam3->setText(text3); m_Controls->tlParam4->setText(text4); m_Controls->btnDoIt->setEnabled(true); m_Controls->cbHideOrig->setEnabled(true); } void QmitkBasicImageProcessing::StartButtonClicked() { if(!m_SelectedImageNode->GetNode()) return; this->BusyCursorOn(); mitk::Image::Pointer newImage; try { newImage = dynamic_cast(m_SelectedImageNode->GetNode()->GetData()); } catch ( std::exception &e ) { QString exceptionString = "An error occured during image loading:\n"; exceptionString.append( e.what() ); QMessageBox::warning( NULL, "Basic Image Processing", exceptionString , QMessageBox::Ok, QMessageBox::NoButton ); this->BusyCursorOff(); return; } // check if input image is valid, casting does not throw exception when casting from 'NULL-Object' if ( (! newImage) || (newImage->IsInitialized() == false) ) { this->BusyCursorOff(); QMessageBox::warning( NULL, "Basic Image Processing", "Input image is broken or not initialized. Returning.", QMessageBox::Ok, QMessageBox::NoButton ); return; } // check if operation is done on 4D a image time step if(newImage->GetDimension() > 3) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(newImage); timeSelector->SetTimeNr( ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos() ); timeSelector->Update(); newImage = timeSelector->GetOutput(); } // check if image or vector image ImageType::Pointer itkImage = ImageType::New(); VectorImageType::Pointer itkVecImage = VectorImageType::New(); int isVectorImage = newImage->GetPixelType().GetNumberOfComponents(); if(isVectorImage > 1) { CastToItkImage( newImage, itkVecImage ); } else { CastToItkImage( newImage, itkImage ); } std::stringstream nameAddition(""); int param1 = m_Controls->sbParam1->value(); int param2 = m_Controls->sbParam2->value(); double dparam1 = m_Controls->dsbParam1->value(); double dparam2 = m_Controls->dsbParam2->value(); double dparam3 = m_Controls->dsbParam3->value(); try{ switch (m_SelectedAction) { case GAUSSIAN: { GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New(); gaussianFilter->SetInput( itkImage ); gaussianFilter->SetVariance( param1 ); gaussianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(gaussianFilter->GetOutput())->Clone(); nameAddition << "_Gaussian_var_" << param1; std::cout << "Gaussian filtering successful." << std::endl; break; } case MEDIAN: { MedianFilterType::Pointer medianFilter = MedianFilterType::New(); MedianFilterType::InputSizeType size; size.Fill(param1); medianFilter->SetRadius( size ); medianFilter->SetInput(itkImage); medianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(medianFilter->GetOutput())->Clone(); nameAddition << "_Median_radius_" << param1; std::cout << "Median Filtering successful." << std::endl; break; } case TOTALVARIATION: { if(isVectorImage > 1) { VectorTotalVariationFilterType::Pointer TVFilter = VectorTotalVariationFilterType::New(); TVFilter->SetInput( itkVecImage.GetPointer() ); TVFilter->SetNumberIterations(param1); TVFilter->SetLambda(double(param2)/1000.); TVFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone(); } else { ImagePTypeToFloatPTypeCasterType::Pointer floatCaster = ImagePTypeToFloatPTypeCasterType::New(); floatCaster->SetInput( itkImage ); floatCaster->Update(); FloatImageType::Pointer fImage = floatCaster->GetOutput(); TotalVariationFilterType::Pointer TVFilter = TotalVariationFilterType::New(); TVFilter->SetInput( fImage.GetPointer() ); TVFilter->SetNumberIterations(param1); TVFilter->SetLambda(double(param2)/1000.); TVFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone(); } nameAddition << "_TV_Iter_" << param1 << "_L_" << param2; std::cout << "Total Variation Filtering successful." << std::endl; break; } case DILATION: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); DilationFilterType::Pointer dilationFilter = DilationFilterType::New(); dilationFilter->SetInput( itkImage ); dilationFilter->SetKernel( binaryBall ); dilationFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(dilationFilter->GetOutput())->Clone(); nameAddition << "_Dilated_by_" << param1; std::cout << "Dilation successful." << std::endl; break; } case EROSION: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); ErosionFilterType::Pointer erosionFilter = ErosionFilterType::New(); erosionFilter->SetInput( itkImage ); erosionFilter->SetKernel( binaryBall ); erosionFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(erosionFilter->GetOutput())->Clone(); nameAddition << "_Eroded_by_" << param1; std::cout << "Erosion successful." << std::endl; break; } case OPENING: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); OpeningFilterType::Pointer openFilter = OpeningFilterType::New(); openFilter->SetInput( itkImage ); openFilter->SetKernel( binaryBall ); openFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(openFilter->GetOutput())->Clone(); nameAddition << "_Opened_by_" << param1; std::cout << "Opening successful." << std::endl; break; } case CLOSING: { BallType binaryBall; binaryBall.SetRadius( param1 ); binaryBall.CreateStructuringElement(); ClosingFilterType::Pointer closeFilter = ClosingFilterType::New(); closeFilter->SetInput( itkImage ); closeFilter->SetKernel( binaryBall ); closeFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(closeFilter->GetOutput())->Clone(); nameAddition << "_Closed_by_" << param1; std::cout << "Closing successful." << std::endl; break; } case GRADIENT: { GradientFilterType::Pointer gradientFilter = GradientFilterType::New(); gradientFilter->SetInput( itkImage ); gradientFilter->SetSigma( param1 ); gradientFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(gradientFilter->GetOutput())->Clone(); nameAddition << "_Gradient_sigma_" << param1; std::cout << "Gradient calculation successful." << std::endl; break; } case LAPLACIAN: { // the laplace filter requires a float type image as input, we need to cast the itkImage // to correct type ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New(); caster->SetInput( itkImage ); caster->Update(); FloatImageType::Pointer fImage = caster->GetOutput(); LaplacianFilterType::Pointer laplacianFilter = LaplacianFilterType::New(); laplacianFilter->SetInput( fImage ); laplacianFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(laplacianFilter->GetOutput())->Clone(); nameAddition << "_Second_Derivative"; std::cout << "Laplacian filtering successful." << std::endl; break; } case SOBEL: { // the sobel filter requires a float type image as input, we need to cast the itkImage // to correct type ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New(); caster->SetInput( itkImage ); caster->Update(); FloatImageType::Pointer fImage = caster->GetOutput(); SobelFilterType::Pointer sobelFilter = SobelFilterType::New(); sobelFilter->SetInput( fImage ); sobelFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(sobelFilter->GetOutput())->Clone(); nameAddition << "_Sobel"; std::cout << "Edge Detection successful." << std::endl; break; } case THRESHOLD: { ThresholdFilterType::Pointer thFilter = ThresholdFilterType::New(); thFilter->SetLowerThreshold(param1 < param2 ? param1 : param2); thFilter->SetUpperThreshold(param2 > param1 ? param2 : param1); thFilter->SetInsideValue(1); thFilter->SetOutsideValue(0); thFilter->SetInput(itkImage); thFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(thFilter->GetOutput())->Clone(); nameAddition << "_Threshold"; std::cout << "Thresholding successful." << std::endl; break; } case INVERSION: { InversionFilterType::Pointer invFilter = InversionFilterType::New(); mitk::ScalarType min = newImage->GetScalarValueMin(); mitk::ScalarType max = newImage->GetScalarValueMax(); invFilter->SetMaximum( max + min ); invFilter->SetInput(itkImage); invFilter->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(invFilter->GetOutput())->Clone(); nameAddition << "_Inverted"; std::cout << "Image inversion successful." << std::endl; break; } case DOWNSAMPLING: { ResampleImageFilterType::Pointer downsampler = ResampleImageFilterType::New(); downsampler->SetInput( itkImage ); NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New(); downsampler->SetInterpolator( interpolator ); downsampler->SetDefaultPixelValue( 0 ); ResampleImageFilterType::SpacingType spacing = itkImage->GetSpacing(); spacing *= (double) param1; downsampler->SetOutputSpacing( spacing ); downsampler->SetOutputOrigin( itkImage->GetOrigin() ); downsampler->SetOutputDirection( itkImage->GetDirection() ); ResampleImageFilterType::SizeType size = itkImage->GetLargestPossibleRegion().GetSize(); for ( int i = 0; i < 3; ++i ) { size[i] /= param1; } downsampler->SetSize( size ); downsampler->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(downsampler->GetOutput())->Clone(); nameAddition << "_Downsampled_by_" << param1; std::cout << "Downsampling successful." << std::endl; break; } case FLIPPING: { FlipImageFilterType::Pointer flipper = FlipImageFilterType::New(); flipper->SetInput( itkImage ); itk::FixedArray flipAxes; for(int i=0; i<3; ++i) { if(i == param1) { flipAxes[i] = true; } else { flipAxes[i] = false; } } flipper->SetFlipAxes(flipAxes); flipper->UpdateLargestPossibleRegion(); newImage = mitk::ImportItkImage(flipper->GetOutput())->Clone(); std::cout << "Image flipping successful." << std::endl; break; } case RESAMPLING: { std::string selectedInterpolator; ResampleImageFilterType::Pointer resampler = ResampleImageFilterType::New(); switch (m_SelectedInterpolation) { case LINEAR: { LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New(); resampler->SetInterpolator(interpolator); selectedInterpolator = "Linear"; break; } case NEAREST: { NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New(); resampler->SetInterpolator(interpolator); selectedInterpolator = "Nearest"; break; } default: { LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New(); resampler->SetInterpolator(interpolator); selectedInterpolator = "Linear"; break; } } resampler->SetInput( itkImage ); resampler->SetOutputOrigin( itkImage->GetOrigin() ); ImageType::SizeType input_size = itkImage->GetLargestPossibleRegion().GetSize(); ImageType::SpacingType input_spacing = itkImage->GetSpacing(); ImageType::SizeType output_size; ImageType::SpacingType output_spacing; output_size[0] = input_size[0] * (input_spacing[0] / dparam1); output_size[1] = input_size[1] * (input_spacing[1] / dparam2); output_size[2] = input_size[2] * (input_spacing[2] / dparam3); output_spacing [0] = dparam1; output_spacing [1] = dparam2; output_spacing [2] = dparam3; resampler->SetSize( output_size ); resampler->SetOutputSpacing( output_spacing ); resampler->SetOutputDirection( itkImage->GetDirection() ); resampler->UpdateLargestPossibleRegion(); ImageType::Pointer resampledImage = resampler->GetOutput(); newImage = mitk::ImportItkImage( resampledImage )->Clone(); nameAddition << "_Resampled_" << selectedInterpolator; std::cout << "Resampling successful." << std::endl; break; } case RESCALE: { FloatImageType::Pointer floatImage = FloatImageType::New(); CastToItkImage( newImage, floatImage ); itk::RescaleIntensityImageFilter::Pointer filter = itk::RescaleIntensityImageFilter::New(); filter->SetInput(0, floatImage); filter->SetOutputMinimum(dparam1); filter->SetOutputMaximum(dparam2); filter->Update(); floatImage = filter->GetOutput(); newImage = mitk::Image::New(); newImage->InitializeByItk(floatImage.GetPointer()); newImage->SetVolume(floatImage->GetBufferPointer()); nameAddition << "_Rescaled"; std::cout << "Rescaling successful." << std::endl; break; } default: this->BusyCursorOff(); return; } } catch (...) { this->BusyCursorOff(); QMessageBox::warning(NULL, "Warning", "Problem when applying filter operation. Check your input..."); return; } newImage->DisconnectPipeline(); // adjust level/window to new image mitk::LevelWindow levelwindow; levelwindow.SetAuto( newImage ); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); levWinProp->SetLevelWindow( levelwindow ); // compose new image name std::string name = m_SelectedImageNode->GetNode()->GetName(); if (name.find(".pic.gz") == name.size() -7 ) { name = name.substr(0,name.size() -7); } name.append( nameAddition.str() ); // create final result MITK data storage node mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "levelwindow", levWinProp ); result->SetProperty( "name", mitk::StringProperty::New( name.c_str() ) ); result->SetData( newImage ); // for vector images, a different mapper is needed if(isVectorImage > 1) { mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); result->SetMapper(1,mapper); } // reset GUI to ease further processing // this->ResetOneImageOpPanel(); // add new image to data storage and set as active to ease further processing GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() ); if ( m_Controls->cbHideOrig->isChecked() == true ) m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); // TODO!! m_Controls->m_ImageSelector1->SetSelectedNode(result); // show the results mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->BusyCursorOff(); } void QmitkBasicImageProcessing::SelectAction2(int operation) { // check which operation the user has selected and set parameters and GUI accordingly switch (operation) { case 2: m_SelectedOperation = ADD; break; case 3: m_SelectedOperation = SUBTRACT; break; case 4: m_SelectedOperation = MULTIPLY; break; case 5: m_SelectedOperation = DIVIDE; break; case 6: m_SelectedOperation = RESAMPLE_TO; break; case 8: m_SelectedOperation = AND; break; case 9: m_SelectedOperation = OR; break; case 10: m_SelectedOperation = XOR; break; default: // this->ResetTwoImageOpPanel(); return; } m_Controls->tlImage2->setEnabled(true); m_Controls->m_ImageSelector2->setEnabled(true); m_Controls->btnDoIt2->setEnabled(true); } void QmitkBasicImageProcessing::StartButton2Clicked() { mitk::Image::Pointer newImage1 = dynamic_cast (m_SelectedImageNode->GetNode()->GetData()); mitk::Image::Pointer newImage2 = dynamic_cast (m_Controls->m_ImageSelector2->GetSelectedNode()->GetData()); // check if images are valid if( (!newImage1) || (!newImage2) || (newImage1->IsInitialized() == false) || (newImage2->IsInitialized() == false) ) { itkGenericExceptionMacro(<< "At least one of the input images are broken or not initialized. Returning"); return; } this->BusyCursorOn(); // this->ResetTwoImageOpPanel(); // check if 4D image and use filter on correct time step int time = ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos(); if(newImage1->GetDimension() > 3) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(newImage1); timeSelector->SetTimeNr( time ); timeSelector->UpdateLargestPossibleRegion(); newImage1 = timeSelector->GetOutput(); newImage1->DisconnectPipeline(); timeSelector->SetInput(newImage2); timeSelector->SetTimeNr( time ); timeSelector->UpdateLargestPossibleRegion(); newImage2 = timeSelector->GetOutput(); newImage2->DisconnectPipeline(); } // reset GUI for better usability // this->ResetTwoImageOpPanel(); ImageType::Pointer itkImage1 = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); CastToItkImage( newImage1, itkImage1 ); CastToItkImage( newImage2, itkImage2 ); // Remove temp image newImage2 = NULL; std::string nameAddition = ""; try { switch (m_SelectedOperation) { case ADD: { AddFilterType::Pointer addFilter = AddFilterType::New(); addFilter->SetInput1( itkImage1 ); addFilter->SetInput2( itkImage2 ); addFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(addFilter->GetOutput())->Clone(); nameAddition = "_Added"; } break; case SUBTRACT: { SubtractFilterType::Pointer subFilter = SubtractFilterType::New(); subFilter->SetInput1( itkImage1 ); subFilter->SetInput2( itkImage2 ); subFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(subFilter->GetOutput())->Clone(); nameAddition = "_Subtracted"; } break; case MULTIPLY: { MultiplyFilterType::Pointer multFilter = MultiplyFilterType::New(); multFilter->SetInput1( itkImage1 ); multFilter->SetInput2( itkImage2 ); multFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(multFilter->GetOutput())->Clone(); nameAddition = "_Multiplied"; } break; case DIVIDE: { DivideFilterType::Pointer divFilter = DivideFilterType::New(); divFilter->SetInput1( itkImage1 ); divFilter->SetInput2( itkImage2 ); divFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(divFilter->GetOutput())->Clone(); nameAddition = "_Divided"; } break; case AND: { AndImageFilterType::Pointer andFilter = AndImageFilterType::New(); andFilter->SetInput1( itkImage1 ); andFilter->SetInput2( itkImage2 ); andFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(andFilter->GetOutput())->Clone(); nameAddition = "_AND"; break; } case OR: { OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput1( itkImage1 ); orFilter->SetInput2( itkImage2 ); orFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(orFilter->GetOutput())->Clone(); nameAddition = "_OR"; break; } case XOR: { XorImageFilterType::Pointer xorFilter = XorImageFilterType::New(); xorFilter->SetInput1( itkImage1 ); xorFilter->SetInput2( itkImage2 ); xorFilter->UpdateLargestPossibleRegion(); newImage1 = mitk::ImportItkImage(xorFilter->GetOutput())->Clone(); nameAddition = "_XOR"; break; } case RESAMPLE_TO: { itk::NearestNeighborInterpolateImageFunction::Pointer nn_interpolator = itk::NearestNeighborInterpolateImageFunction::New(); ResampleImageFilterType2::Pointer resampleFilter = ResampleImageFilterType2::New(); resampleFilter->SetInput( itkImage1 ); resampleFilter->SetReferenceImage( itkImage2 ); resampleFilter->SetUseReferenceImage( true ); resampleFilter->SetInterpolator( nn_interpolator ); resampleFilter->SetDefaultPixelValue( 0 ); try { resampleFilter->UpdateLargestPossibleRegion(); } catch( const itk::ExceptionObject &e) { MITK_WARN << "Updating resampling filter failed. "; MITK_WARN << "REASON: " << e.what(); } ImageType::Pointer resampledImage = resampleFilter->GetOutput(); newImage1 = mitk::ImportItkImage( resampledImage )->Clone(); nameAddition = "_Resampled"; break; } default: std::cout << "Something went wrong..." << std::endl; this->BusyCursorOff(); return; } } catch (const itk::ExceptionObject& e ) { this->BusyCursorOff(); QMessageBox::warning(NULL, "ITK Exception", e.what() ); QMessageBox::warning(NULL, "Warning", "Problem when applying arithmetic operation to two images. Check dimensions of input images."); return; } // disconnect pipeline; images will not be reused newImage1->DisconnectPipeline(); itkImage1 = NULL; itkImage2 = NULL; // adjust level/window to new image and compose new image name mitk::LevelWindow levelwindow; levelwindow.SetAuto( newImage1 ); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); levWinProp->SetLevelWindow( levelwindow ); std::string name = m_SelectedImageNode->GetNode()->GetName(); if (name.find(".pic.gz") == name.size() -7 ) { name = name.substr(0,name.size() -7); } // create final result MITK data storage node mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty( "levelwindow", levWinProp ); result->SetProperty( "name", mitk::StringProperty::New( (name + nameAddition ).c_str() )); result->SetData( newImage1 ); GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() ); // show only the newly created image m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); m_Controls->m_ImageSelector2->GetSelectedNode()->SetProperty( "visible", mitk::BoolProperty::New(false) ); // show the newly created image mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->BusyCursorOff(); } void QmitkBasicImageProcessing::SelectInterpolator(int interpolator) { switch (interpolator) { case 0: { m_SelectedInterpolation = LINEAR; break; } case 1: { m_SelectedInterpolation = NEAREST; break; } } } diff --git a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h index e727fb698b..0e11c58395 100644 --- a/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h +++ b/Plugins/org.mitk.gui.qt.basicimageprocessing/src/internal/QmitkBasicImageProcessingView.h @@ -1,189 +1,185 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #if !defined(QmitkBasicImageProcessingView_H__INCLUDED) #define QmitkBasicImageProcessingView_H__INCLUDED #include "QmitkFunctionality.h" #include #include "ui_QmitkBasicImageProcessingViewControls.h" #include "QmitkStepperAdapter.h" -#include - #include /*! \brief This module allows to use some basic image processing filters for preprocessing, image enhancement and testing purposes Several basic ITK image processing filters, like denoising, morphological and edge detection are encapsulated in this module and can be selected via a list and an intuitive parameter input. The selected filter will be applied on the image, and a new image showing the output is displayed as result. Also, some image arithmetic operations are available. Images can be 3D or 4D. In the 4D case, the filters work on the 3D image selected via the time slider. The result is also a 3D image. \sa QmitkFunctionality, QObject \class QmitkBasicImageProcessing \author Tobias Schwarz \version 1.0 (3M3) \date 2009-05-10 \ingroup Bundles */ class BASICIMAGEPROCESSING_EXPORT QmitkBasicImageProcessing : public QmitkFunctionality { Q_OBJECT public: /*! \brief default constructor */ QmitkBasicImageProcessing(); /*! \brief default destructor */ virtual ~QmitkBasicImageProcessing(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); virtual void Activated(); /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(std::vector nodes); protected slots: /* * When an action is selected in the "one image ops" list box */ void SelectAction(int action); /* * When an action is selected in the "two image ops" list box */ void SelectAction2(int operation); /* * The "Execute" button in the "one image ops" box was triggered */ void StartButtonClicked(); /* * The "Execute" button in the "two image ops" box was triggered */ void StartButton2Clicked(); /* * Switch between the one and the two image operations GUI */ void ChangeGUI(); void SelectInterpolator(int interpolator); private: /* * After a one image operation, reset the "one image ops" panel */ void ResetOneImageOpPanel(); /* * Helper method to reset the parameter set panel */ void ResetParameterPanel(); /* * After a two image operation, reset the "two image ops" panel */ void ResetTwoImageOpPanel(); /*! * controls containing sliders for scrolling through the slices */ Ui::QmitkBasicImageProcessingViewControls *m_Controls; //mitk::DataNode* m_SelectedImageNode; mitk::DataStorageSelection::Pointer m_SelectedImageNode; QmitkStepperAdapter* m_TimeStepperAdapter; - berry::ISelectionListener::Pointer m_SelectionListener; - enum ActionType { NOACTIONSELECTED, CATEGORY_DENOISING, GAUSSIAN, MEDIAN, TOTALVARIATION, CATEGORY_MORPHOLOGICAL, DILATION, EROSION, OPENING, CLOSING, CATEGORY_EDGE_DETECTION, GRADIENT, LAPLACIAN, SOBEL, CATEGORY_MISC, THRESHOLD, INVERSION, DOWNSAMPLING, FLIPPING, RESAMPLING, RESCALE } m_SelectedAction; enum OperationType{ TWOIMAGESNOACTIONSELECTED, CATEGORY_ARITHMETIC, ADD, SUBTRACT, MULTIPLY, DIVIDE, RESAMPLE_TO, CATEGORY_BOOLEAN, AND, OR, XOR } m_SelectedOperation; enum InterpolationType{ LINEAR, NEAREST } m_SelectedInterpolation; }; #endif // !defined(QmitkBasicImageProcessing_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp index cc9f0de959..00434e7155 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesPreferencesPage.cpp @@ -1,262 +1,260 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CommandLineModulesPreferencesPage.h" #include "CommandLineModulesViewConstants.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkDirectoryListWidget.h" #include "QmitkFileListWidget.h" //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::CommandLineModulesPreferencesPage() : m_MainControl(0) , m_DebugOutput(0) , m_ShowAdvancedWidgets(0) , m_OutputDirectory(0) , m_TemporaryDirectory(0) , m_ModulesDirectories(0) , m_ModulesFiles(0) , m_GridLayoutForLoadCheckboxes(0) , m_LoadFromHomeDir(0) , m_LoadFromHomeDirCliModules(0) , m_LoadFromCurrentDir(0) , m_LoadFromCurrentDirCliModules(0) , m_LoadFromApplicationDir(0) , m_LoadFromApplicationDirCliModules(0) , m_LoadFromAutoLoadPathDir(0) , m_ValidationMode(0) , m_MaximumNumberProcesses(0) , m_CLIPreferencesNode(0) { } //----------------------------------------------------------------------------- CommandLineModulesPreferencesPage::~CommandLineModulesPreferencesPage() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService::Pointer prefService - = berry::Platform::GetServiceRegistry() - .GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - std::string id = "/" + CommandLineModulesViewConstants::VIEW_ID; + QString id = "/" + CommandLineModulesViewConstants::VIEW_ID; m_CLIPreferencesNode = prefService->GetSystemPreferences()->Node(id); m_MainControl = new QWidget(parent); m_TemporaryDirectory = new ctkDirectoryButton(m_MainControl); m_TemporaryDirectory->setCaption("Select a directory for temporary files ... "); m_OutputDirectory = new ctkDirectoryButton(m_MainControl); m_OutputDirectory->setCaption("Select a default directory for output files ... "); m_ModulesDirectories = new QmitkDirectoryListWidget(m_MainControl); m_ModulesDirectories->m_Label->setText("Select directories to scan:"); m_ModulesFiles = new QmitkFileListWidget(m_MainControl); m_ModulesFiles->m_Label->setText("Select additional executables:"); m_DebugOutput = new QCheckBox(m_MainControl); m_DebugOutput->setToolTip("Output debugging information to the console."); m_ShowAdvancedWidgets = new QCheckBox(m_MainControl); m_ShowAdvancedWidgets->setToolTip("If selected, additional widgets appear\nin front-end for advanced users."); m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl); m_LoadFromAutoLoadPathDir->setText("CTK_MODULE_LOAD_PATH"); m_LoadFromAutoLoadPathDir->setToolTip("Scan the directory specified by\nthe environment variable CTK_MODULE_LOAD_PATH."); m_LoadFromAutoLoadPathDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDir = new QCheckBox(m_MainControl); m_LoadFromApplicationDir->setText("install dir"); m_LoadFromApplicationDir->setToolTip("Scan the directory where\nthe application is installed."); m_LoadFromApplicationDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromApplicationDirCliModules = new QCheckBox(m_MainControl); m_LoadFromApplicationDirCliModules->setText("install dir/cli-modules"); m_LoadFromApplicationDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the installation directory."); m_LoadFromApplicationDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDir = new QCheckBox(m_MainControl); m_LoadFromHomeDir->setText("home dir"); m_LoadFromHomeDir->setToolTip("Scan the users home directory."); m_LoadFromHomeDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromHomeDirCliModules = new QCheckBox(m_MainControl); m_LoadFromHomeDirCliModules->setText("home dir/cli-modules"); m_LoadFromHomeDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the users home directory."); m_LoadFromHomeDirCliModules->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDir = new QCheckBox(m_MainControl); m_LoadFromCurrentDir->setText("current dir"); m_LoadFromCurrentDir->setToolTip("Scan the current working directory\nfrom where the application was launched."); m_LoadFromCurrentDir->setLayoutDirection(Qt::RightToLeft); m_LoadFromCurrentDirCliModules = new QCheckBox(m_MainControl); m_LoadFromCurrentDirCliModules->setText("current dir/cli-modules"); m_LoadFromCurrentDirCliModules->setToolTip("Scan the 'cli-modules' sub-directory\nwithin the current working directory \n from where the application was launched."); m_LoadFromCurrentDirCliModules->setLayoutDirection(Qt::RightToLeft); m_GridLayoutForLoadCheckboxes = new QGridLayout; m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDir, 0, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromApplicationDirCliModules, 0, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDir, 1, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromHomeDirCliModules, 1, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDir, 2, 0); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromCurrentDirCliModules, 2, 1); m_GridLayoutForLoadCheckboxes->addWidget(m_LoadFromAutoLoadPathDir, 3, 1); m_ValidationMode = new QComboBox(m_MainControl); m_ValidationMode->addItem("strict", ctkCmdLineModuleManager::STRICT_VALIDATION); m_ValidationMode->addItem("none", ctkCmdLineModuleManager::SKIP_VALIDATION); m_ValidationMode->addItem("weak", ctkCmdLineModuleManager::WEAK_VALIDATION); m_ValidationMode->setCurrentIndex(0); m_MaximumNumberProcesses = new QSpinBox(m_MainControl); m_MaximumNumberProcesses->setMinimum(1); m_MaximumNumberProcesses->setMaximum(1000000); m_XmlTimeoutInSeconds = new QSpinBox(m_MainControl); m_XmlTimeoutInSeconds->setMinimum(1); m_XmlTimeoutInSeconds->setMaximum(3600); QFormLayout *formLayout = new QFormLayout; formLayout->addRow("show debug output:", m_DebugOutput); formLayout->addRow("show advanced widgets:", m_ShowAdvancedWidgets); formLayout->addRow("XML time-out (secs):", m_XmlTimeoutInSeconds); formLayout->addRow("XML validation mode:", m_ValidationMode); formLayout->addRow("max. concurrent processes:", m_MaximumNumberProcesses); formLayout->addRow("scan:", m_GridLayoutForLoadCheckboxes); formLayout->addRow("additional module directories:", m_ModulesDirectories); formLayout->addRow("additional modules:", m_ModulesFiles); formLayout->addRow("temporary directory:", m_TemporaryDirectory); formLayout->addRow("default output directory:", m_OutputDirectory); m_MainControl->setLayout(formLayout); this->Update(); } //----------------------------------------------------------------------------- QWidget* CommandLineModulesPreferencesPage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- std::string CommandLineModulesPreferencesPage::ConvertToStdString(const QStringList& list) { std::string output; for (int i = 0; i < list.count(); i++) { QString path = list[i] + ";"; output += path.toStdString(); } return output; } //----------------------------------------------------------------------------- bool CommandLineModulesPreferencesPage::PerformOk() { - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory().toStdString()); - m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory().toStdString()); + m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, m_TemporaryDirectory->directory()); + m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, m_OutputDirectory->directory()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, m_ShowAdvancedWidgets->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, m_LoadFromApplicationDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, m_LoadFromHomeDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, m_LoadFromCurrentDirCliModules->isChecked()); m_CLIPreferencesNode->PutBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked()); - std::string paths = this->ConvertToStdString(m_ModulesDirectories->directories()); + QString paths = m_ModulesDirectories->directories().join(";"); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, paths); - std::string modules = this->ConvertToStdString(m_ModulesFiles->files()); + QString modules = m_ModulesFiles->files().join(";"); m_CLIPreferencesNode->Put(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, modules); int currentValidationMode = m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); if (currentValidationMode != m_ValidationMode->currentIndex()) { QMessageBox msgBox; msgBox.setText("Changing the XML validation mode will require a restart of the application."); msgBox.exec(); } m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, m_ValidationMode->currentIndex()); m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, m_XmlTimeoutInSeconds->value()); m_CLIPreferencesNode->PutInt(CommandLineModulesViewConstants::MAX_CONCURRENT, m_MaximumNumberProcesses->value()); return true; } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::PerformCancel() { } //----------------------------------------------------------------------------- void CommandLineModulesPreferencesPage::Update() { QString fallbackTmpDir = QDir::tempPath(); - m_TemporaryDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir.toStdString()))); + m_TemporaryDirectory->setDirectory(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir)); QString fallbackOutputDir = QDir::homePath(); - m_OutputDirectory->setDirectory(QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir.toStdString()))); + m_OutputDirectory->setDirectory(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackOutputDir)); m_ShowAdvancedWidgets->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); m_DebugOutput->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false)); m_LoadFromApplicationDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false)); m_LoadFromApplicationDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true)); m_LoadFromHomeDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false)); m_LoadFromHomeDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false)); m_LoadFromCurrentDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false)); m_LoadFromCurrentDirCliModules->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false)); m_LoadFromAutoLoadPathDir->setChecked(m_CLIPreferencesNode->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false)); - QString paths = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); + QString paths = m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, ""); QStringList directoryList = paths.split(";", QString::SkipEmptyParts); m_ModulesDirectories->setDirectories(directoryList); - QString files = QString::fromStdString(m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); + QString files = m_CLIPreferencesNode->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, ""); QStringList fileList = files.split(";", QString::SkipEmptyParts); m_ModulesFiles->setFiles(fileList); m_ValidationMode->setCurrentIndex(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2)); m_XmlTimeoutInSeconds->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30)); // 30 secs = QProcess default timeout m_MaximumNumberProcesses->setValue(m_CLIPreferencesNode->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4)); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp index 562bc66d84..aa8da191b6 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesView.cpp @@ -1,552 +1,550 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include #include +#include // Qmitk #include "CommandLineModulesView.h" #include "CommandLineModulesViewConstants.h" #include "CommandLineModulesViewControls.h" #include "CommandLineModulesPreferencesPage.h" #include "QmitkCmdLineModuleFactoryGui.h" #include "QmitkCmdLineModuleGui.h" #include "QmitkCmdLineModuleRunner.h" // Qt #include #include #include #include #include #include #include #include // CTK #include #include #include #include #include #include #include #include #include #include //----------------------------------------------------------------------------- CommandLineModulesView::CommandLineModulesView() : m_Controls(NULL) , m_Parent(NULL) , m_Layout(NULL) , m_ModuleManager(NULL) , m_ModuleBackend(NULL) , m_DirectoryWatcher(NULL) , m_TemporaryDirectoryName("") , m_MaximumConcurrentProcesses(4) , m_CurrentlyRunningProcesses(0) , m_DebugOutput(false) , m_XmlTimeoutSeconds(30) // 30 seconds = QProcess default timeout. { } //----------------------------------------------------------------------------- CommandLineModulesView::~CommandLineModulesView() { if (m_ModuleManager != NULL) { delete m_ModuleManager; } if (m_ModuleBackend != NULL) { delete m_ModuleBackend; } if (m_DirectoryWatcher != NULL) { delete m_DirectoryWatcher; } if (m_Layout != NULL) { delete m_Layout; } for (int i = 0; i < m_ListOfModules.size(); i++) { delete m_ListOfModules[i]; } } //----------------------------------------------------------------------------- void CommandLineModulesView::SetFocus() { this->m_Controls->m_ComboBox->setFocus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::CreateQtPartControl( QWidget *parent ) { m_Parent = parent; if (!m_Controls) { // We create CommandLineModulesViewControls, which derives from the Qt generated class. m_Controls = new CommandLineModulesViewControls(parent); // Create a layout to contain a display of QmitkCmdLineModuleRunner. m_Layout = new QVBoxLayout(m_Controls->m_RunningWidgets); m_Layout->setContentsMargins(0,0,0,0); m_Layout->setSpacing(0); // This must be done independent of other preferences, as we need it before // we create the ctkCmdLineModuleManager to initialise the Cache. this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); // Start to create the command line module infrastructure. m_ModuleBackend = new ctkCmdLineModuleBackendLocalProcess(); m_ModuleManager = new ctkCmdLineModuleManager(m_ValidationMode, m_TemporaryDirectoryName); // Set the main object, the ctkCmdLineModuleManager onto all the objects that need it. m_Controls->m_ComboBox->SetManager(m_ModuleManager); m_DirectoryWatcher = new ctkCmdLineModuleDirectoryWatcher(m_ModuleManager); connect(this->m_DirectoryWatcher, SIGNAL(errorDetected(QString)), this, SLOT(OnDirectoryWatcherErrorsDetected(QString))); m_ModuleManager->registerBackend(m_ModuleBackend); // Setup the remaining preferences. this->RetrieveAndStorePreferenceValues(); // Connect signals to slots after we have set up GUI. connect(this->m_Controls->m_RunButton, SIGNAL(pressed()), this, SLOT(OnRunButtonPressed())); connect(this->m_Controls->m_RestoreDefaults, SIGNAL(pressed()), this, SLOT(OnRestoreButtonPressed())); connect(this->m_Controls->m_ComboBox, SIGNAL(actionChanged(QAction*)), this, SLOT(OnActionChanged(QAction*))); connect(this->m_Controls->m_TabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(OnTabCloseRequested(int))); connect(this->m_Controls->m_ClearXMLCache, SIGNAL(pressed()), this, SLOT(OnClearCache())); connect(this->m_Controls->m_ReloadModules, SIGNAL(pressed()), this, SLOT(OnReloadModules())); this->UpdateRunButtonEnabledStatus(); } } //----------------------------------------------------------------------------- berry::IBerryPreferences::Pointer CommandLineModulesView::RetrievePreferences() { - berry::IPreferencesService::Pointer prefService - = berry::Platform::GetServiceRegistry() - .GetServiceById(berry::IPreferencesService::ID); - + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); assert( prefService ); - std::string id = "/" + CommandLineModulesViewConstants::VIEW_ID; + QString id = "/" + CommandLineModulesViewConstants::VIEW_ID; berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(id)) .Cast(); assert( prefs ); return prefs; } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreTemporaryDirectoryPreferenceValues() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); QString fallbackTmpDir = QDir::tempPath(); - m_TemporaryDirectoryName = QString::fromStdString( - prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir.toStdString())); + m_TemporaryDirectoryName = + prefs->Get(CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME, fallbackTmpDir); } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStoreValidationMode() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); int value = prefs->GetInt(CommandLineModulesViewConstants::XML_VALIDATION_MODE, 2); if (value == 0) { m_ValidationMode = ctkCmdLineModuleManager::STRICT_VALIDATION; } else if (value == 1) { m_ValidationMode = ctkCmdLineModuleManager::SKIP_VALIDATION; } else { m_ValidationMode = ctkCmdLineModuleManager::WEAK_VALIDATION; } } //----------------------------------------------------------------------------- void CommandLineModulesView::RetrieveAndStorePreferenceValues() { berry::IBerryPreferences::Pointer prefs = this->RetrievePreferences(); QString fallbackHomeDir = QDir::homePath(); - m_OutputDirectoryName = QString::fromStdString( - prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackHomeDir.toStdString())); + m_OutputDirectoryName = + prefs->Get(CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME, fallbackHomeDir); m_MaximumConcurrentProcesses = prefs->GetInt(CommandLineModulesViewConstants::MAX_CONCURRENT, 4); m_XmlTimeoutSeconds = prefs->GetInt(CommandLineModulesViewConstants::XML_TIMEOUT_SECS, 30); m_ModuleManager->setTimeOutForXMLRetrieval(m_XmlTimeoutSeconds * 1000); // preference is in seconds, underlying CTK library in milliseconds. // Get the flag for debug output, useful when parsing all the XML. m_DebugOutput = prefs->GetBool(CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME, false); m_DirectoryWatcher->setDebug(m_DebugOutput); // Show/Hide the advanced widgets this->m_Controls->SetAdvancedWidgetsVisible(prefs->GetBool(CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME, false)); bool loadApplicationDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR, false); bool loadApplicationDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES, true); bool loadHomeDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR, false); bool loadHomeDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES, false); bool loadCurrentDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR, false); bool loadCurrentDirCliModules = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES, false); bool loadAutoLoadDir = prefs->GetBool(CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR, false); // Get some default application paths. // Here we can use the preferences to set up the builder, ctkCmdLineModuleDefaultPathBuilder builder; if (loadApplicationDir) builder.addApplicationDir(); if (loadApplicationDirCliModules) builder.addApplicationDir("cli-modules"); if (loadHomeDir) builder.addHomeDir(); if (loadHomeDirCliModules) builder.addHomeDir("cli-modules"); if (loadCurrentDir) builder.addCurrentDir(); if (loadCurrentDirCliModules) builder.addCurrentDir("cli-modules"); if (loadAutoLoadDir) builder.addCtkModuleLoadPath(); // and then we ask the builder to set up the paths. QStringList defaultPaths = builder.getDirectoryList(); // We get additional directory paths from preferences. - QString pathString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, "")); + QString pathString = prefs->Get(CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME, ""); QStringList additionalPaths = pathString.split(";", QString::SkipEmptyParts); // Combine the sets of directory paths. QStringList totalPaths; totalPaths << defaultPaths; totalPaths << additionalPaths; - QString additionalModulesString = QString::fromStdString(prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, "")); + QString additionalModulesString = prefs->Get(CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME, ""); QStringList additionalModules = additionalModulesString.split(";", QString::SkipEmptyParts); // OnPreferencesChanged can be called for each preference in a dialog box, so // when you hit "OK", it is called repeatedly, whereas we want to only call these only once. if (m_DirectoryPaths != totalPaths) { m_DirectoryPaths = totalPaths; m_DirectoryWatcher->setDirectories(totalPaths); } if (m_ModulePaths != additionalModules) { m_ModulePaths = additionalModules; m_DirectoryWatcher->setAdditionalModules(additionalModules); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnPreferencesChanged(const berry::IBerryPreferences* /*prefs*/) { this->RetrieveAndStoreTemporaryDirectoryPreferenceValues(); this->RetrieveAndStoreValidationMode(); this->RetrieveAndStorePreferenceValues(); } //----------------------------------------------------------------------------- ctkCmdLineModuleReference CommandLineModulesView::GetReferenceByFullName(QString fullName) { ctkCmdLineModuleReference result; QList references = this->m_ModuleManager->moduleReferences(); ctkCmdLineModuleReference ref; foreach(ref, references) { QString name = ref.description().categoryDotTitle(); if (name == fullName) { result = ref; } } return result; } //----------------------------------------------------------------------------- void CommandLineModulesView::OnActionChanged(QAction* action) { QString fullName = action->objectName(); ctkCmdLineModuleReference ref = this->GetReferenceByFullName(fullName); // ref should never be invalid, as the menu was generated from each ctkCmdLineModuleReference. // But just to be sure ... if invalid, don't do anything. if (ref) { // Check if we already have the reference. int tabIndex = -1; for (int i = 0; i < m_ListOfModules.size(); i++) { ctkCmdLineModuleReference tabsReference = m_ListOfModules[i]->moduleReference(); if (ref.location() == tabsReference.location()) { tabIndex = i; break; } } // i.e. we found a matching tab, so just switch to it. if (tabIndex != -1) { m_Controls->m_TabWidget->setCurrentIndex(tabIndex); } else // i.e. we did not find a matching tab { // In this case, we need to create a new tab, and give // it a GUI for the user to setup the parameters with. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEnd = factory.create(ref); QmitkCmdLineModuleGui *theGui = dynamic_cast(frontEnd); // Add to list and tab wigdget m_ListOfModules.push_back(frontEnd); int tabIndex = m_Controls->m_TabWidget->addTab(theGui->getGui(), ref.description().title()); m_Controls->m_TabWidget->setTabToolTip(tabIndex, ref.description().title() + ":" + ref.xmlValidationErrorString()); // Here lies a small caveat. // // The XML may specify a default output file name. // However, this will probably have no file path, so we should probably add one. // Otherwise you will likely be trying to write in the application installation folder // eg. C:/Program Files (Windows) or /Applications/ (Mac) // // Also, we may find that 3rd party apps crash when they can't write. // So lets plan for the worst and hope for the best :-) QString parameterName; QList parameters; parameters = frontEnd->parameters("image", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("file", ctkCmdLineModuleFrontend::Output); parameters << frontEnd->parameters("geometry", ctkCmdLineModuleFrontend::Output); foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QString outputFileName = frontEnd->value(parameterName, ctkCmdLineModuleFrontend::DisplayRole).toString(); QFileInfo outputFileInfo(outputFileName); if (outputFileInfo.absoluteFilePath() != outputFileName) { QDir defaultOutputDir(m_OutputDirectoryName); QFileInfo replacementFileInfo(defaultOutputDir, outputFileName); frontEnd->setValue(parameterName, replacementFileInfo.absoluteFilePath(), ctkCmdLineModuleFrontend::DisplayRole); } } } } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnTabCloseRequested(int tabNumber) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; m_Controls->m_TabWidget->removeTab(tabNumber); m_ListOfModules.removeAt(tabNumber); delete frontEnd; } //----------------------------------------------------------------------------- void CommandLineModulesView::AskUserToSelectAModule() const { QMessageBox msgBox; msgBox.setText("Please select a module!"); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRestoreButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { ctkCmdLineModuleFrontend *frontEnd = m_ListOfModules[tabNumber]; frontEnd->resetValues(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnRunButtonPressed() { int tabNumber = m_Controls->m_TabWidget->currentIndex(); if (tabNumber >= 0) { // 1. Create a new QmitkCmdLineModuleRunner to represent the running widget. QmitkCmdLineModuleRunner *widget = new QmitkCmdLineModuleRunner(m_Controls->m_RunningWidgets); widget->SetDataStorage(this->GetDataStorage()); widget->SetManager(m_ModuleManager); widget->SetOutputDirectory(m_OutputDirectoryName); // 2. Create a new front end. QmitkCmdLineModuleFactoryGui factory(this->GetDataStorage()); ctkCmdLineModuleFrontend *frontEndOnCurrentTab = m_ListOfModules[tabNumber]; QmitkCmdLineModuleGui *frontEndGuiOnCurrentTab = dynamic_cast(frontEndOnCurrentTab); ctkCmdLineModuleReference currentTabFrontendReferences = frontEndGuiOnCurrentTab->moduleReference(); ctkCmdLineModuleFrontend *newFrontEnd = factory.create(currentTabFrontendReferences); QmitkCmdLineModuleGui *newFrontEndGui = dynamic_cast(newFrontEnd); widget->SetFrontend(newFrontEndGui); m_Layout->insertWidget(0, widget); // 3. Copy parameters. This MUST come after widget->SetFrontEnd newFrontEndGui->copyParameters(*frontEndGuiOnCurrentTab); newFrontEndGui->setParameterContainerEnabled(false); // 4. Connect widget signals to here, to count how many jobs running. connect(widget, SIGNAL(started()), this, SLOT(OnJobStarted())); connect(widget, SIGNAL(finished()), this, SLOT(OnJobFinished())); // 5. GO. widget->Run(); } else { this->AskUserToSelectAModule(); } } //----------------------------------------------------------------------------- void CommandLineModulesView::UpdateRunButtonEnabledStatus() { if (m_CurrentlyRunningProcesses >= m_MaximumConcurrentProcesses) { m_Controls->m_RunButton->setEnabled(false); } else { m_Controls->m_RunButton->setEnabled(true); } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobStarted() { m_CurrentlyRunningProcesses++; this->UpdateRunButtonEnabledStatus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnJobFinished() { m_CurrentlyRunningProcesses--; this->UpdateRunButtonEnabledStatus(); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnDirectoryWatcherErrorsDetected(const QString& errorMsg) { ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMsg); } //----------------------------------------------------------------------------- void CommandLineModulesView::OnClearCache() { if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnClearCache(): starting"; } m_ModuleManager->clearCache(); if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnClearCache(): finishing"; } } //----------------------------------------------------------------------------- void CommandLineModulesView::OnReloadModules() { QList urls; QList moduleRefs = m_ModuleManager->moduleReferences(); foreach (ctkCmdLineModuleReference ref, moduleRefs) { urls.push_back(ref.location()); } if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): unloading:" << urls; } foreach (ctkCmdLineModuleReference ref, moduleRefs) { m_ModuleManager->unregisterModule(ref); } if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): reloading."; } QList refResults = QtConcurrent::blockingMapped(urls, ctkCmdLineModuleConcurrentRegister(m_ModuleManager, m_DebugOutput)); if (this->m_DebugOutput) { qDebug() << "CommandLineModulesView::OnReloadModules(): finished."; } QString errorMessages = ctkCmdLineModuleUtils::errorMessagesFromModuleRegistration(refResults, m_ModuleManager->validationMode()); ctkCmdLineModuleUtils::messageBoxForModuleRegistration(errorMessages); } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp index 784083245c..4ea6224042 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.cpp @@ -1,34 +1,34 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CommandLineModulesViewConstants.h" -const std::string CommandLineModulesViewConstants::VIEW_ID = "org.mitk.gui.qt.cmdlinemodules"; -const std::string CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME = "temporary directory"; -const std::string CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME = "output directory"; -const std::string CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME = "module directories"; -const std::string CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME = "module files"; -const std::string CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME = "debug output"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR = "load from application dir"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR = "load from home dir"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR = "load from current dir"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR = "load from auto-load dir"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES = "load from application dir/cli-modules"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES = "load from home dir/cli-modules"; -const std::string CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES = "load from current dir/cli-modules"; -const std::string CommandLineModulesViewConstants::XML_VALIDATION_MODE = "xml validation mode"; -const std::string CommandLineModulesViewConstants::XML_TIMEOUT_SECS = "xml time-out"; -const std::string CommandLineModulesViewConstants::MAX_CONCURRENT = "max concurrent processes"; -const std::string CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME = "show advanced widgets"; +const QString CommandLineModulesViewConstants::VIEW_ID = "org.mitk.gui.qt.cmdlinemodules"; +const QString CommandLineModulesViewConstants::TEMPORARY_DIRECTORY_NODE_NAME = "temporary directory"; +const QString CommandLineModulesViewConstants::OUTPUT_DIRECTORY_NODE_NAME = "output directory"; +const QString CommandLineModulesViewConstants::MODULE_DIRECTORIES_NODE_NAME = "module directories"; +const QString CommandLineModulesViewConstants::MODULE_FILES_NODE_NAME = "module files"; +const QString CommandLineModulesViewConstants::DEBUG_OUTPUT_NODE_NAME = "debug output"; +const QString CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR = "load from application dir"; +const QString CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR = "load from home dir"; +const QString CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR = "load from current dir"; +const QString CommandLineModulesViewConstants::LOAD_FROM_AUTO_LOAD_DIR = "load from auto-load dir"; +const QString CommandLineModulesViewConstants::LOAD_FROM_APPLICATION_DIR_CLI_MODULES = "load from application dir/cli-modules"; +const QString CommandLineModulesViewConstants::LOAD_FROM_HOME_DIR_CLI_MODULES = "load from home dir/cli-modules"; +const QString CommandLineModulesViewConstants::LOAD_FROM_CURRENT_DIR_CLI_MODULES = "load from current dir/cli-modules"; +const QString CommandLineModulesViewConstants::XML_VALIDATION_MODE = "xml validation mode"; +const QString CommandLineModulesViewConstants::XML_TIMEOUT_SECS = "xml time-out"; +const QString CommandLineModulesViewConstants::MAX_CONCURRENT = "max concurrent processes"; +const QString CommandLineModulesViewConstants::SHOW_ADVANCED_WIDGETS_NAME = "show advanced widgets"; diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h index 2e2595b05f..4b309f3344 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/CommandLineModulesViewConstants.h @@ -1,125 +1,124 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef CommandLineModulesViewConstants_h #define CommandLineModulesViewConstants_h #include -#include /** * \class CommandLineModulesViewConstants * \brief Structure to define a namespace for constants used privately within this view. * \author Matt Clarkson (m.clarkson@ucl.ac.uk) * \ingroup org_mitk_gui_qt_cmdlinemodules_internal */ struct CommandLineModulesViewConstants { /** * \brief The name of the preferences node containing the temporary directory. */ - static const std::string TEMPORARY_DIRECTORY_NODE_NAME; + static const QString TEMPORARY_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the output directory. */ - static const std::string OUTPUT_DIRECTORY_NODE_NAME; + static const QString OUTPUT_DIRECTORY_NODE_NAME; /** * \brief The name of the preferences node containing the list of directories to scan. */ - static const std::string MODULE_DIRECTORIES_NODE_NAME; + static const QString MODULE_DIRECTORIES_NODE_NAME; /** * \brief The name of the preferences node containing the additional files to add to the module list. */ - static const std::string MODULE_FILES_NODE_NAME; + static const QString MODULE_FILES_NODE_NAME; /** * \brief The name of the preferences node containing whether we are producing debug output. */ - static const std::string DEBUG_OUTPUT_NODE_NAME; + static const QString DEBUG_OUTPUT_NODE_NAME; /** * \brief The name of the preferences node containing whether we are displaying advanced widgets. */ - static const std::string SHOW_ADVANCED_WIDGETS_NAME; + static const QString SHOW_ADVANCED_WIDGETS_NAME; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the application directory. */ - static const std::string LOAD_FROM_APPLICATION_DIR; + static const QString LOAD_FROM_APPLICATION_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the "application directory/cli-modules". */ - static const std::string LOAD_FROM_APPLICATION_DIR_CLI_MODULES; + static const QString LOAD_FROM_APPLICATION_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users home directory. */ - static const std::string LOAD_FROM_HOME_DIR; + static const QString LOAD_FROM_HOME_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the users "home directory/cli-modules". */ - static const std::string LOAD_FROM_HOME_DIR_CLI_MODULES; + static const QString LOAD_FROM_HOME_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications current working directory. */ - static const std::string LOAD_FROM_CURRENT_DIR; + static const QString LOAD_FROM_CURRENT_DIR; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the applications "current working directory/cli-modules". */ - static const std::string LOAD_FROM_CURRENT_DIR_CLI_MODULES; + static const QString LOAD_FROM_CURRENT_DIR_CLI_MODULES; /** * \brief The name of the preferences node containing a boolean describing whether * we are loading modules from the directory specified in CTK_MODULE_LOAD_PATH. */ - static const std::string LOAD_FROM_AUTO_LOAD_DIR; + static const QString LOAD_FROM_AUTO_LOAD_DIR; /** * \brief The name of the preferences node containing the validation mode. */ - static const std::string XML_VALIDATION_MODE; + static const QString XML_VALIDATION_MODE; /** * \brief The name of the preferences node containing the timeout in seconds for XML retrieval. */ - static const std::string XML_TIMEOUT_SECS; + static const QString XML_TIMEOUT_SECS; /** * \brief The name of the preferences node containing the maximum number of concurrent processes. */ - static const std::string MAX_CONCURRENT; + static const QString MAX_CONCURRENT; /** * \brief The View ID = org.mitk.gui.qt.cmdlinemodules, and should match that in plugin.xml. */ - static const std::string VIEW_ID; + static const QString VIEW_ID; }; #endif // CommandLineModulesViewConstants_h diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp index b1e533c218..bd63e1235b 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.cpp @@ -1,359 +1,362 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFunctionality.h" #include "internal/QmitkFunctionalityUtil.h" // other includes #include // mitk Includes #include #include // berry Includes #include #include #include +#include // Qmitk Includes #include // Qt Includes #include #include #include #include QmitkFunctionality::QmitkFunctionality() : m_Parent(0) , m_Active(false) , m_Visible(false) , m_SelectionProvider(0) , m_HandlesMultipleDataStorages(false) , m_InDataStorageChanged(false) { - m_PreferencesService = - berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); } void QmitkFunctionality::SetHandleMultipleDataStorages(bool multiple) { m_HandlesMultipleDataStorages = multiple; } bool QmitkFunctionality::HandlesMultipleDataStorages() const { return m_HandlesMultipleDataStorages; } mitk::DataStorage::Pointer QmitkFunctionality::GetDataStorage() const { - mitk::IDataStorageService::Pointer service = - berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); + mitk::IDataStorageService* service = this->GetSite()->GetService(); - if (service.IsNotNull()) + if (service != nullptr) { if (m_HandlesMultipleDataStorages) return service->GetActiveDataStorage()->GetDataStorage(); else return service->GetDefaultDataStorage()->GetDataStorage(); } return 0; } mitk::DataStorage::Pointer QmitkFunctionality::GetDefaultDataStorage() const { - mitk::IDataStorageService::Pointer service = - berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); - - return service->GetDefaultDataStorage()->GetDataStorage(); + mitk::IDataStorageService* service = this->GetSite()->GetService(); + if (service != nullptr) + { + return service->GetDefaultDataStorage()->GetDataStorage(); + } + return 0; } void QmitkFunctionality::CreatePartControl(void* parent) { // scrollArea QScrollArea* scrollArea = new QScrollArea; //QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea); scrollArea->setFrameShadow(QFrame::Plain); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // m_Parent m_Parent = new QWidget; //m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); this->CreateQtPartControl(m_Parent); //scrollAreaLayout->addWidget(m_Parent); //scrollArea->setLayout(scrollAreaLayout); // set the widget now scrollArea->setWidgetResizable(true); scrollArea->setWidget(m_Parent); // add the scroll area to the real parent (the view tabbar) QWidget* parentQWidget = static_cast(parent); QVBoxLayout* parentLayout = new QVBoxLayout(parentQWidget); parentLayout->setMargin(0); parentLayout->setSpacing(0); parentLayout->addWidget(scrollArea); // finally set the layout containing the scroll area to the parent widget (= show it) parentQWidget->setLayout(parentLayout); this->AfterCreateQtPartControl(); } void QmitkFunctionality::AfterCreateQtPartControl() { // REGISTER DATASTORAGE LISTENER this->GetDefaultDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy ) ); // REGISTER PREFERENCES LISTENER berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) prefs->OnChanged.AddListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // REGISTER FOR WORKBENCH SELECTION EVENTS - m_BlueBerrySelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter(this - , &QmitkFunctionality::BlueBerrySelectionChanged)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_BlueBerrySelectionListener); + m_BlueBerrySelectionListener.reset(new berry::SelectionChangedAdapter( + this, + &QmitkFunctionality::BlueBerrySelectionChanged) + ); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener( + /*"org.mitk.views.datamanager",*/ m_BlueBerrySelectionListener.data()); // REGISTER A SELECTION PROVIDER - QmitkFunctionalitySelectionProvider::Pointer _SelectionProvider - = QmitkFunctionalitySelectionProvider::New(this); + QmitkFunctionalitySelectionProvider::Pointer _SelectionProvider( + new QmitkFunctionalitySelectionProvider(this)); m_SelectionProvider = _SelectionProvider.GetPointer(); this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(m_SelectionProvider)); // EMULATE INITIAL SELECTION EVENTS // by default a a multi widget is always available this->StdMultiWidgetAvailable(*this->GetActiveStdMultiWidget()); // send datamanager selection this->OnSelectionChanged(this->GetDataManagerSelection()); // send preferences changed event this->OnPreferencesChanged(this->GetPreferences().Cast().GetPointer()); } void QmitkFunctionality::ClosePart() { } void QmitkFunctionality::ClosePartProxy() { this->GetDefaultDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeAddedProxy ) ); this->GetDefaultDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeRemovedProxy) ); this->GetDefaultDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &QmitkFunctionality::NodeChangedProxy ) ); berry::IBerryPreferences::Pointer prefs = this->GetPreferences().Cast(); if(prefs.IsNotNull()) { prefs->OnChanged.RemoveListener(berry::MessageDelegate1(this, &QmitkFunctionality::OnPreferencesChanged)); // flush the preferences here (disabled, everyone should flush them by themselves at the right moment) // prefs->Flush(); } // REMOVE SELECTION PROVIDER this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(NULL)); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) { - s->RemovePostSelectionListener(m_BlueBerrySelectionListener); + s->RemovePostSelectionListener(m_BlueBerrySelectionListener.data()); } - this->ClosePart(); + this->ClosePart(); } QmitkFunctionality::~QmitkFunctionality() { this->Register(); this->ClosePartProxy(); this->UnRegister(false); } void QmitkFunctionality::OnPreferencesChanged( const berry::IBerryPreferences* ) { } -void QmitkFunctionality::BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection) +void QmitkFunctionality::BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, + const berry::ISelection::ConstPointer& selection) { if(sourcepart.IsNull() || sourcepart->GetSite()->GetId() != "org.mitk.views.datamanager") return; mitk::DataNodeSelection::ConstPointer _DataNodeSelection = selection.Cast(); this->OnSelectionChanged(this->DataNodeSelectionToVector(_DataNodeSelection)); } bool QmitkFunctionality::IsVisible() const { return m_Visible; } void QmitkFunctionality::SetFocus() { } void QmitkFunctionality::Activated() { } void QmitkFunctionality::Deactivated() { } void QmitkFunctionality::StdMultiWidgetAvailable( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::StdMultiWidgetNotAvailable() { } void QmitkFunctionality::DataStorageChanged() { } QmitkStdMultiWidget* QmitkFunctionality::GetActiveStdMultiWidget( bool reCreateWidget ) { QmitkStdMultiWidget* activeStdMultiWidget = 0; berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->GetActiveEditor(); if (reCreateWidget || editor.Cast().IsNull() ) { - mitk::IDataStorageService::Pointer service = - berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); + mitk::IDataStorageService* service = this->GetSite()->GetService(); - mitk::DataStorageEditorInput::Pointer editorInput; - editorInput = new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ); + mitk::DataStorageEditorInput::Pointer editorInput( + new mitk::DataStorageEditorInput( service->GetActiveDataStorage() )); // open a new multi-widget editor, but do not give it the focus berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false, berry::IWorkbenchPage::MATCH_ID); activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } else if (editor.Cast().IsNotNull()) { activeStdMultiWidget = editor.Cast()->GetStdMultiWidget(); } return activeStdMultiWidget; } void QmitkFunctionality::HandleException( const char* str, QWidget* parent, bool showDialog ) const { //itkGenericOutputMacro( << "Exception caught: " << str ); MITK_ERROR << str; if ( showDialog ) { QMessageBox::critical ( parent, "Exception caught!", str ); } } void QmitkFunctionality::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const { HandleException( e.what(), parent, showDialog ); } void QmitkFunctionality::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { } void QmitkFunctionality::WaitCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) ); } void QmitkFunctionality::BusyCursorOn() { QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) ); } void QmitkFunctionality::WaitCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::BusyCursorOff() { this->RestoreOverrideCursor(); } void QmitkFunctionality::RestoreOverrideCursor() { QApplication::restoreOverrideCursor(); } berry::IPreferences::Pointer QmitkFunctionality::GetPreferences() const { - berry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock(); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); // const_cast workaround for bad programming: const uncorrectness this->GetViewSite() should be const - std::string id = "/" + (const_cast(this))->GetViewSite()->GetId(); - return prefService.IsNotNull() ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); + QString id = "/" + (const_cast(this))->GetViewSite()->GetId(); + return prefService != nullptr ? prefService->GetSystemPreferences()->Node(id): berry::IPreferences::Pointer(0); } void QmitkFunctionality::Visible() { } void QmitkFunctionality::Hidden() { } bool QmitkFunctionality::IsExclusiveFunctionality() const { return true; } void QmitkFunctionality::SetVisible( bool visible ) { m_Visible = visible; } void QmitkFunctionality::SetActivated( bool activated ) { m_Active = activated; } bool QmitkFunctionality::IsActivated() const { return m_Active; } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h index 37427b53a9..a11bf8298e 100755 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionality.h @@ -1,396 +1,392 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKFUNCTIONALITY_H_ #define QMITKFUNCTIONALITY_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif //# blueberry stuff #include #include #include #include //# mitk stuff #include #include "mitkDataNodeSelection.h" #include #include //# forward declarations namespace mitk { class DataNode; } namespace berry { struct IBerryPreferences; } class QmitkFunctionalitySelectionProvider; /// /// \ingroup org_mitk_gui_qt_common_legacy /// /// \class QmitkFunctionality /// /// \brief The base class of all MITK related blueberry views (~ in the old version of MITK, this was called "Functionality") /// /// QmitkFunctionality provides several convenience methods that eases the introduction of a new view: /// ///
    ///
  1. Access to the DataStorage (~ the shared data repository) ///
  2. Access to the StdMultiWidget (the 2x2 RenderWindow arrangement) ///
  3. Access to and update notification for the functionality/view preferences ///
  4. Access to and update notification for the current DataNode selection / to DataNode selection events send through the SelectionService ///
  5. Methods to send DataNode selections through the SelectionService ///
  6. Some events for unproblematic inter-View communication (e.g. when to add/remove interactors) ///
  7. Some minor important convenience methods (like changing the mouse cursor/exception handling) ///
/// /// Please use the Activated/Deactivated method to add/remove interactors, disabling multiwidget crosshair or anything which may /// "affect" other functionalities. For further reading please have a look at QmitkFunctionality::IsExclusiveFunctionality(). /// class MITK_QT_COMMON_LEGACY QmitkFunctionality : public berry::QtViewPart { //# public virtual methods which can be overwritten public: /// /// Creates smartpointer typedefs /// berryObjectMacro(QmitkFunctionality); /// /// Nothing to do in the standard ctor. Initiliaze your GUI in CreateQtPartControl(QWidget*) /// \see berry::QtViewPart::CreateQtPartControl(QWidget*) /// QmitkFunctionality(); /// /// Disconnects all standard event listeners /// virtual ~QmitkFunctionality(); /// /// Called, when the WorkbenchPart gets closed /// by the user directly or by closing the whole /// app (e.g. for removing event listeners) /// virtual void ClosePart(); /// /// Called when the selection in the workbench changed /// virtual void OnSelectionChanged(std::vector /*nodes*/); /// /// Called when the preferences object of this view changed. /// \see GetPreferences() /// virtual void OnPreferencesChanged(const berry::IBerryPreferences*); /// /// Make this view manage multiple DataStorage. If set to true GetDataStorage() /// will return the currently active DataStorage (and not the default one). /// \see GetDataStorage() /// void SetHandleMultipleDataStorages(bool multiple); /// /// \return true if this view handles multiple DataStorages, false otherwise /// bool HandlesMultipleDataStorages() const; /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when a StdMultiWidget is available. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); /// /// Called when no StdMultiWidget is available anymore. Should not be used anymore, see GetActiveStdMultiWidget() /// \see GetActiveStdMultiWidget() /// virtual void StdMultiWidgetNotAvailable(); /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Activated(); /// /// \return true if this view is currently activated, false otherwise /// bool IsActivated() const; /// /// Only called when IsExclusiveFunctionality() returns true. /// \see IsExclusiveFunctionality() /// virtual void Deactivated(); /// /// Some functionalities need to add special interactors, removes the crosshair from the stdmultiwidget, etc. /// In this case the functionality has to tidy up when changing to another functionality /// which also wants to change the "default configuration". In the old Qt3-based /// version of MITK, two functionalities could never be opened at the same time so that the /// methods Activated() and Deactivated() were the right place for the functionalitites to /// add/remove their interactors, etc. This is still true for the new MITK Workbench, /// but as there can be several functionalities visible at the same time, the behaviour concerning /// when Activated() and Deactivated() are called has changed: /// /// 1. Activated() and Deactivated() are only called if IsExclusiveFunctionality() returns true /// /// 2. If only one standalone functionality is or becomes visible, Activated() will be called on that functionality /// /// 3. If two or more standalone functionalities are visible, /// Activated() will be called on the functionality that receives focus, Deactivated() will be called /// on the one that looses focus, gets hidden or closed /// /// /// As a consequence of 1. if you overwrite IsExclusiveFunctionality() and let it return false, you /// signalize the MITK Workbench that this functionality does nothing to the "default configuration" /// and can easily be visible while other functionalities are also visible. /// /// By default the method returns true. /// /// \return true if this functionality is meant to work as a standalone view, false otherwise /// virtual bool IsExclusiveFunctionality() const; /// /// Informs other parts of the workbench that node is selected via the blueberry selection service. /// void FireNodeSelected(mitk::DataNode* node); /// /// Informs other parts of the workbench that the nodes are selected via the blueberry selection service. /// void FireNodesSelected(std::vector nodes); /// /// Called when this functionality becomes visible ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Visible(); /// /// \return true if this view is currently visible, false otherwise /// bool IsVisible() const; /// /// Called when this functionality is hidden ( no matter what IsExclusiveFunctionality() returns ) /// virtual void Hidden(); //# protected virtual methods which can be overwritten protected: /// /// Called when a DataStorage Add event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeAdded(const mitk::DataNode* node); /// /// Called when a DataStorage Changed event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeChanged(const mitk::DataNode* /*node*/); /// /// Called when a DataStorage Remove event was thrown. May be reimplemented /// by deriving classes. /// virtual void NodeRemoved(const mitk::DataNode* node); /// /// Called when a DataStorage add *or* remove *or* change event was thrown. May be reimplemented /// by deriving classes. /// virtual void DataStorageChanged(); /// /// \return the selection of the currently active part of the workbench or an empty vector /// if nothing is selected /// std::vector GetCurrentSelection() const; /// /// Returns the current selection made in the datamanager bundle or an empty vector /// if nothing`s selected or if the bundle does not exist /// std::vector GetDataManagerSelection() const; /// /// Returns the Preferences object for this Functionality. /// Important: When refering to this preferences, e.g. in a PreferencePage: The ID /// for this preferences object is "/", e.g. "/org.mitk.views.datamanager" /// berry::IPreferences::Pointer GetPreferences() const; /// /// Returns the default or the currently active DataStorage if m_HandlesMultipleDataStorages /// is set to true /// \see SetHandleMultipleDataStorages(bool) /// \see HandlesMultipleDataStorages() /// mitk::DataStorage::Pointer GetDataStorage() const; /// /// \return always returns the default DataStorage /// mitk::DataStorage::Pointer GetDefaultDataStorage() const; /// /// Returns the default and active StdMultiWidget. /// \param reCreateWidget a boolean flag to en-/disable the attept to re-create the StdWidget /// If there is not StdMultiWidget yet a new one is /// created in this method when called with default parameter! /// QmitkStdMultiWidget* GetActiveStdMultiWidget( bool reCreateWidget = true); /// /// Outputs an error message to the console and displays a message box containing /// the exception description. /// \param e the exception which should be handled /// \param showDialog controls, whether additionally a message box should be /// displayed to inform the user that something went wrong /// void HandleException( std::exception& e, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Calls HandleException ( std::exception&, QWidget*, bool ) internally /// \see HandleException ( std::exception&, QWidget*, bool ) /// void HandleException( const char* str, QWidget* parent = NULL, bool showDialog = true ) const; /// /// Convenient method to set and reset a wait cursor ("hourglass") /// void WaitCursorOn(); /// /// Convenient method to restore the standard cursor /// void WaitCursorOff(); /// /// Convenient method to set and reset a busy cursor /// void BusyCursorOn(); /// /// Convenient method to restore the standard cursor /// void BusyCursorOff(); /// /// Convenient method to restore the standard cursor /// void RestoreOverrideCursor(); //# other public methods which should not be overwritten public: /// /// Creates a scroll area for this view and calls CreateQtPartControl then /// void CreatePartControl(void* parent); /// /// Called when this view receives the focus. Same as Activated() /// \see Activated() /// void SetFocus(); /// /// Called when a DataStorage Add Event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeAdded afterwards. /// \see m_InDataStorageChanged /// void NodeAddedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage remove event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeRemoved afterwards. /// \see m_InDataStorageChanged /// void NodeRemovedProxy(const mitk::DataNode* node); /// /// Called when a DataStorage changed event was thrown. Sets /// m_InDataStorageChanged to true and calls NodeChanged afterwards. /// \see m_InDataStorageChanged /// void NodeChangedProxy(const mitk::DataNode* node); /// /// Toggles the visible flag m_Visible /// void SetVisible(bool visible); /// /// Toggles the activated flag m_Activated /// void SetActivated(bool activated); /// /// Called, when the WorkbenchPart gets closed for removing event listeners /// Internally this method calls ClosePart after it removed the listeners registered /// by QmitkFunctionality. By having this proxy method the user does not have to /// call QmitkFunctionality::ClosePart() when overwriting ClosePart() /// void ClosePartProxy(); //# other protected methods which should not be overwritten (or which are deprecated) protected: /// /// Called immediately after CreateQtPartControl(). /// Here standard event listeners for a QmitkFunctionality are registered /// void AfterCreateQtPartControl(); /// /// code to activate the last visible functionality /// void ActivateLastVisibleFunctionality(); /// /// reactions to selection events from data manager (and potential other senders) /// - void BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); + void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, const berry::ISelection::ConstPointer& selection); /// /// Converts a mitk::DataNodeSelection to a std::vector (possibly empty /// std::vector DataNodeSelectionToVector(mitk::DataNodeSelection::ConstPointer currentSelection) const; //# protected fields protected: /// /// helper stuff to observe BlueBerry selections /// friend struct berry::SelectionChangedAdapter; /// /// Saves the parent of this view (this is the scrollarea created in CreatePartControl(void*) /// \see CreatePartControl(void*) /// QWidget* m_Parent; /// /// Saves if this view is the currently active one. /// bool m_Active; /// /// Saves if this view is visible /// bool m_Visible; //# private fields: private: /// /// Holds the current selection (selection made by this Functionality !!!) /// QmitkFunctionalitySelectionProvider* m_SelectionProvider; /// /// object to observe BlueBerry selections /// - berry::ISelectionListener::Pointer m_BlueBerrySelectionListener; + QScopedPointer m_BlueBerrySelectionListener; /// /// Saves if this view handles multiple datastorages /// bool m_HandlesMultipleDataStorages; /// /// Saves if this class is currently working on DataStorage changes. /// This is a protector variable to avoid recursive calls on event listener functions. bool m_InDataStorageChanged; /// /// saves all visible functionalities /// std::set m_VisibleFunctionalities; - /// - /// The Preferences Service to retrieve and store preferences. - /// - berry::IPreferencesService::WeakPtr m_PreferencesService; }; #endif /*QMITKFUNCTIONALITY_H_*/ diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp index 23a73ddf6e..0386f218c4 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.cpp @@ -1,222 +1,220 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFunctionalityCoordinator.h" #include "QmitkFunctionality.h" #include #include #include #include QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator() : m_StandaloneFuntionality(0) { } void QmitkFunctionalityCoordinator::Start() { - berry::PlatformUI::GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this)); - std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); - for (std::vector::iterator i = wnds.begin(); - i != wnds.end(); ++i) + berry::PlatformUI::GetWorkbench()->AddWindowListener(this); + QList wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); + for (auto i = wnds.begin(); i != wnds.end(); ++i) { - (*i)->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); + (*i)->GetPartService()->AddPartListener(this); } } void QmitkFunctionalityCoordinator::Stop() { if (!berry::PlatformUI::IsWorkbenchRunning()) return; - berry::PlatformUI::GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this)); - std::vector wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); - for (std::vector::iterator i = wnds.begin(); - i != wnds.end(); ++i) + berry::PlatformUI::GetWorkbench()->RemoveWindowListener(this); + QList wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows()); + for (auto i = wnds.begin(); i != wnds.end(); ++i) { - (*i)->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this)); + (*i)->GetPartService()->RemovePartListener(this); } } QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator() { } berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const { return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED; } -void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef ) +void QmitkFunctionalityCoordinator::PartActivated( const berry::IWorkbenchPartReference::Pointer& partRef ) { // change the active standalone functionality this->ActivateStandaloneFunctionality(partRef.GetPointer()); } -void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer /*partRef*/ ) +void QmitkFunctionalityCoordinator::PartDeactivated( const berry::IWorkbenchPartReference::Pointer& /*partRef*/ ) { // nothing to do here: see PartActivated() } -void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef ) +void QmitkFunctionalityCoordinator::PartOpened( const berry::IWorkbenchPartReference::Pointer& partRef ) { // check for multiwidget and inform views that it is available now if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { for (std::set::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetAvailable(*(partRef ->GetPart(false).Cast()->GetStdMultiWidget())); } } else { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality } } } -void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) +void QmitkFunctionalityCoordinator::PartClosed( const berry::IWorkbenchPartReference::Pointer& partRef ) { // check for multiwidget and inform views that it not available any more if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); for (std::set::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget())); (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence } } else { // check for functionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { // deactivate on close ( the standalone functionality may still be activated ) this->DeactivateStandaloneFunctionality(partRef.GetPointer(), 0); // and set pointer to 0 if(m_StandaloneFuntionality == partRef.GetPointer()) m_StandaloneFuntionality = 0; m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality // call PartClosed on the QmitkFunctionality _QmitkFunctionality->ClosePartProxy(); //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden() } } } -void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) +void QmitkFunctionalityCoordinator::PartHidden( const berry::IWorkbenchPartReference::Pointer& partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality != 0) { _QmitkFunctionality->SetVisible(false); _QmitkFunctionality->Hidden(); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.erase(partRef.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if( m_VisibleStandaloneFunctionalities.size() == 1 ) this->ActivateStandaloneFunctionality( *m_VisibleStandaloneFunctionalities.begin() ); } } -void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) +void QmitkFunctionalityCoordinator::PartVisible( const berry::IWorkbenchPartReference::Pointer& partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast(); if(_QmitkFunctionality.IsNotNull()) { _QmitkFunctionality->SetVisible(true); _QmitkFunctionality->Visible(); // tracking of Visible Standalone Functionalities if( _QmitkFunctionality->IsExclusiveFunctionality() ) { m_VisibleStandaloneFunctionalities.insert(partRef.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if( m_VisibleStandaloneFunctionalities.size() == 1 ) this->ActivateStandaloneFunctionality( *m_VisibleStandaloneFunctionalities.begin() ); } } } void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( berry::IWorkbenchPartReference* partRef ) { QmitkFunctionality* functionality = dynamic_cast(partRef->GetPart(false).GetPointer()); if( functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality() ) { MITK_INFO << "**** Activating legacy standalone functionality"; // deactivate old one if necessary this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality, partRef); m_StandaloneFuntionality = partRef; MITK_INFO << "setting active flag"; // call activated on this functionality functionality->SetActivated(true); functionality->Activated(); } else if (dynamic_cast(partRef->GetPart(false).GetPointer()) && m_StandaloneFuntionality != partRef) { this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality, partRef); m_StandaloneFuntionality = partRef; } } void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(berry::IWorkbenchPartReference* partRef, berry::IWorkbenchPartReference* newRef) { if (partRef == 0) return; QmitkFunctionality* functionality = dynamic_cast(partRef->GetPart(false).GetPointer()); if(functionality && functionality->IsActivated()) { functionality->SetActivated(false); functionality->Deactivated(); } else if (mitk::IZombieViewPart* zombie = dynamic_cast(partRef->GetPart(false).GetPointer())) { zombie->ActivatedZombieView(berry::IWorkbenchPartReference::Pointer(newRef)); } } -void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer /*window*/ ) +void QmitkFunctionalityCoordinator::WindowClosed(const berry::IWorkbenchWindow::Pointer& /*window*/ ) { } -void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window ) +void QmitkFunctionalityCoordinator::WindowOpened(const berry::IWorkbenchWindow::Pointer& window ) { - window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); + window->GetPartService()->AddPartListener(this); } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h index 87e50bb480..fe64960f6b 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/QmitkFunctionalityCoordinator.h @@ -1,123 +1,121 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkFunctionalityCoordinator_h #define QmitkFunctionalityCoordinator_h #include #include #include #include #include class QmitkFunctionality; /// /// \ingroup org_mitk_gui_qt_common_legacy /// /// A class which coordinates active QmitkFunctionalities, e.g. calling activated and hidden on them. /// class MITK_QT_COMMON_LEGACY QmitkFunctionalityCoordinator : virtual public berry::IPartListener, virtual public berry::IWindowListener { public: - berryObjectMacro(QmitkFunctionalityCoordinator); - berryNewMacro(QmitkFunctionalityCoordinator); QmitkFunctionalityCoordinator(); virtual ~QmitkFunctionalityCoordinator(); /// /// Add listener /// void Start(); /// /// Remove listener /// void Stop(); //#IPartListener methods (these methods internally call Activated() or other similar methods) /// /// \see IPartListener::GetPartEventTypes() /// berry::IPartListener::Events::Types GetPartEventTypes() const; /// /// \see IPartListener::PartActivated() /// - virtual void PartActivated (berry::IWorkbenchPartReference::Pointer partRef); + virtual void PartActivated (const berry::IWorkbenchPartReference::Pointer& partRef); /// /// \see IPartListener::PartDeactivated() /// - virtual void PartDeactivated(berry::IWorkbenchPartReference::Pointer /*partRef*/); + virtual void PartDeactivated(const berry::IWorkbenchPartReference::Pointer& /*partRef*/); /// /// \see IPartListener::PartOpened() /// - virtual void PartOpened(berry::IWorkbenchPartReference::Pointer partRef); + virtual void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef); /// /// \see IPartListener::PartClosed() /// - virtual void PartClosed (berry::IWorkbenchPartReference::Pointer partRef); + virtual void PartClosed (const berry::IWorkbenchPartReference::Pointer& partRef); /// /// \see IPartListener::PartHidden() /// - virtual void PartHidden (berry::IWorkbenchPartReference::Pointer partRef); + virtual void PartHidden (const berry::IWorkbenchPartReference::Pointer& partRef); /// /// \see IPartListener::PartVisible() /// - virtual void PartVisible (berry::IWorkbenchPartReference::Pointer partRef); + virtual void PartVisible (const berry::IWorkbenchPartReference::Pointer& partRef); /** * Notifies this listener that the given window has been closed. */ - virtual void WindowClosed(berry::IWorkbenchWindow::Pointer window); + virtual void WindowClosed(const berry::IWorkbenchWindow::Pointer& window); /** * Notifies this listener that the given window has been opened. */ - virtual void WindowOpened(berry::IWorkbenchWindow::Pointer /*window*/); + virtual void WindowOpened(const berry::IWorkbenchWindow::Pointer& /*window*/); protected: /// /// Activates the standalone functionality /// void ActivateStandaloneFunctionality(berry::IWorkbenchPartReference *partRef); /// /// Deactivates the standalone functionality /// void DeactivateStandaloneFunctionality(berry::IWorkbenchPartReference *functionality, berry::IWorkbenchPartReference *newRef); /// /// Saves the workbench window /// berry::IWorkbenchWindow::WeakPtr m_Window; /// /// Saves the last part that added interactors /// berry::IWorkbenchPartReference* m_StandaloneFuntionality; /// /// Saves all opened QmitkFclassunctionalities /// std::set m_Functionalities; /// /// Saves all visible QmitkFunctionalities /// std::set m_VisibleStandaloneFunctionalities; }; #endif // QmitkFunctionalityCoordinator_h diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp index 8253eea225..8006e3a14c 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.cpp @@ -1,52 +1,50 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkCommonLegacyActivator.h" #include #include #include void QmitkCommonLegacyActivator::start(ctkPluginContext* context) { Q_UNUSED(context) if(berry::PlatformUI::IsWorkbenchRunning()) { - m_FunctionalityCoordinator = QmitkFunctionalityCoordinator::Pointer(new QmitkFunctionalityCoordinator); - m_FunctionalityCoordinator->Start(); + m_FunctionalityCoordinator.Start(); } else { MITK_ERROR << "BlueBerry Workbench not running!"; } } void QmitkCommonLegacyActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) - m_FunctionalityCoordinator->Stop(); - m_FunctionalityCoordinator = 0; + m_FunctionalityCoordinator.Stop(); } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common_legacy, QmitkCommonLegacyActivator) #endif diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h index 859ec03dd1..d657303207 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkCommonLegacyActivator.h @@ -1,51 +1,51 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKCOMMONLEGACYACTIVATOR_H_ #define QMITKCOMMONLEGACYACTIVATOR_H_ #include #include "QmitkFunctionalityCoordinator.h" /** * \ingroup org_mitk_gui_qt_common_legacy_internal */ class QmitkCommonLegacyActivator : public QObject, public ctkPluginActivator { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_common_legacy") #endif Q_INTERFACES(ctkPluginActivator) public: /** * Sets default StateMachine to EventMapper. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: - QmitkFunctionalityCoordinator::Pointer m_FunctionalityCoordinator; + QmitkFunctionalityCoordinator m_FunctionalityCoordinator; }; #endif /* QMITKCOMMONLEGACYACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp index a29af3483e..6015d8301e 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.cpp @@ -1,62 +1,62 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFunctionalityUtil.h" #include "../QmitkFunctionality.h" QmitkFunctionalitySelectionProvider::QmitkFunctionalitySelectionProvider( QmitkFunctionality* _Functionality ) : m_Functionality(_Functionality) { } QmitkFunctionalitySelectionProvider::~QmitkFunctionalitySelectionProvider() { m_Functionality = 0; } -void QmitkFunctionalitySelectionProvider::AddSelectionChangedListener( berry::ISelectionChangedListener::Pointer listener ) +void QmitkFunctionalitySelectionProvider::AddSelectionChangedListener( berry::ISelectionChangedListener* listener ) { m_SelectionEvents.AddListener(listener); } berry::ISelection::ConstPointer QmitkFunctionalitySelectionProvider::GetSelection() const { return m_CurrentSelection; } -void QmitkFunctionalitySelectionProvider::RemoveSelectionChangedListener( berry::ISelectionChangedListener::Pointer listener ) +void QmitkFunctionalitySelectionProvider::RemoveSelectionChangedListener( berry::ISelectionChangedListener* listener ) { m_SelectionEvents.RemoveListener(listener); } -void QmitkFunctionalitySelectionProvider::SetSelection( berry::ISelection::ConstPointer selection ) +void QmitkFunctionalitySelectionProvider::SetSelection(const berry::ISelection::ConstPointer& selection ) { m_CurrentSelection = selection.Cast(); } -void QmitkFunctionalitySelectionProvider::FireNodesSelected( std::vector nodes ) +void QmitkFunctionalitySelectionProvider::FireNodesSelected(const std::vector& nodes ) { mitk::DataNodeSelection::Pointer sel(new mitk::DataNodeSelection(nodes)); m_CurrentSelection = sel; berry::SelectionChangedEvent::Pointer event(new berry::SelectionChangedEvent(berry::ISelectionProvider::Pointer(this) , m_CurrentSelection)); m_SelectionEvents.selectionChanged(event); } diff --git a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h index c1ab87e7bc..1c2eeb18ab 100644 --- a/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h +++ b/Plugins/org.mitk.gui.qt.common.legacy/src/internal/QmitkFunctionalityUtil.h @@ -1,91 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKFUNCTIONALITYUTIL_H #define QMITKFUNCTIONALITYUTIL_H #include class QmitkFunctionality; #include #include /// /// Internal class for selection providing /// class QmitkFunctionalitySelectionProvider: public berry::ISelectionProvider { public: /// /// Creates smartpointer typedefs /// - berryObjectMacro(QmitkFunctionalitySelectionProvider); - /// - /// Create a selection provider for the given _Functionality - /// - berryNewMacro1Param(QmitkFunctionalitySelectionProvider, QmitkFunctionality*); + berryObjectMacro(QmitkFunctionalitySelectionProvider) + + QmitkFunctionalitySelectionProvider(QmitkFunctionality* _Functionality); + + virtual ~QmitkFunctionalitySelectionProvider(); //# ISelectionProvider methods /// /// \see ISelectionProvider::AddSelectionChangedListener() /// - virtual void AddSelectionChangedListener(berry::ISelectionChangedListener::Pointer listener); + virtual void AddSelectionChangedListener(berry::ISelectionChangedListener* listener); /// /// \see ISelectionProvider::GetSelection() /// virtual berry::ISelection::ConstPointer GetSelection() const; /// /// \see ISelectionProvider::RemoveSelectionChangedListener() /// - virtual void RemoveSelectionChangedListener(berry::ISelectionChangedListener::Pointer listener); + virtual void RemoveSelectionChangedListener(berry::ISelectionChangedListener* listener); /// /// \see ISelectionProvider::SetSelection() /// - virtual void SetSelection(berry::ISelection::ConstPointer selection); + virtual void SetSelection(const berry::ISelection::ConstPointer& selection); /// /// Sends the nodes as selected to the workbench /// - void FireNodesSelected( std::vector nodes ); + void FireNodesSelected(const std::vector& nodes ); protected: - /// - /// nothing to do here - /// - QmitkFunctionalitySelectionProvider(QmitkFunctionality* _Functionality); - /// - /// nothing to do here - /// - virtual ~QmitkFunctionalitySelectionProvider(); /// /// the functionality parent /// QmitkFunctionality* m_Functionality; /// /// Holds the current selection (selection made by m_Functionality !!!) /// mitk::DataNodeSelection::ConstPointer m_CurrentSelection; /// /// The selection events other parts can listen too /// berry::ISelectionChangedListener::Events m_SelectionEvents; }; #endif // QMITKFUNCTIONALITYUTIL_H diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp index c7cb65fafd..cc4c23d5cb 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkDnDFrameWidget.cpp @@ -1,90 +1,91 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include +#include #include #include "internal/QmitkCommonActivator.h" #include #include #include class QmitkDnDFrameWidgetPrivate { public: berry::IPreferences::Pointer GetPreferences() const { - berry::IPreferencesService::Pointer prefService = QmitkCommonActivator::GetInstance()->GetPreferencesService(); - if (prefService.IsNotNull()) + berry::IPreferencesService* prefService = QmitkCommonActivator::GetInstance()->GetPreferencesService(); + if (prefService) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } bool GetOpenEditor() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->GetBool("OpenEditor", true); } return true; } }; QmitkDnDFrameWidget::QmitkDnDFrameWidget(QWidget *parent) : QWidget(parent), d(new QmitkDnDFrameWidgetPrivate()) { setAcceptDrops(true); } QmitkDnDFrameWidget::~QmitkDnDFrameWidget() { } void QmitkDnDFrameWidget::dragEnterEvent( QDragEnterEvent *event ) { // accept drags event->acceptProposedAction(); } void QmitkDnDFrameWidget::dropEvent( QDropEvent * event ) { //open dragged files QList fileNames = event->mimeData()->urls(); if (fileNames.empty()) return; QStringList fileNames2; //TODO Qt 4.7 API //fileNames2.reserve(fileNames.size()); foreach(QUrl url, fileNames) { fileNames2.push_back(url.toLocalFile()); } mitk::WorkbenchUtil::LoadFiles(fileNames2, berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), d->GetOpenEditor()); event->accept(); } diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp index 08fe7dbcb7..1b1e0c0ea7 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.cpp @@ -1,74 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkCommonActivator.h" #include #include QmitkCommonActivator* QmitkCommonActivator::m_Instance = 0; ctkPluginContext* QmitkCommonActivator::m_Context = 0; ctkPluginContext* QmitkCommonActivator::GetContext() { return m_Context; } QmitkCommonActivator* QmitkCommonActivator::GetInstance() { return m_Instance; } -berry::IPreferencesService::Pointer QmitkCommonActivator::GetPreferencesService() +berry::IPreferencesService* QmitkCommonActivator::GetPreferencesService() { - return berry::IPreferencesService::Pointer(m_PrefServiceTracker->getService()); + return m_PrefServiceTracker->getService(); } void QmitkCommonActivator::start(ctkPluginContext* context) { this->m_Instance = this; this->m_Context = context; this->m_PrefServiceTracker.reset(new ctkServiceTracker(context)); if(berry::PlatformUI::IsWorkbenchRunning()) { m_ViewCoordinator.reset(new QmitkViewCoordinator); m_ViewCoordinator->Start(); } else { MITK_ERROR << "BlueBerry Workbench not running!"; } } void QmitkCommonActivator::stop(ctkPluginContext* context) { Q_UNUSED(context) m_ViewCoordinator->Stop(); m_ViewCoordinator.reset(); this->m_PrefServiceTracker.reset(); this->m_Context = 0; this->m_Instance = 0; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_common, QmitkCommonActivator) #endif diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h index 94a96ccd9e..37bcb042f0 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkCommonActivator.h @@ -1,68 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKCOMMONACTIVATOR_H_ #define QMITKCOMMONACTIVATOR_H_ #include #include #include #include "QmitkViewCoordinator.h" /** * \ingroup org_mitk_gui_qt_common_internal * * \brief The plug-in activator for the StateMachine * * When the plug-in is started by the framework, it initializes StateMachine * specific things. */ class QmitkCommonActivator : public QObject, public ctkPluginActivator { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_common") #endif Q_INTERFACES(ctkPluginActivator) public: static ctkPluginContext* GetContext(); static QmitkCommonActivator* GetInstance(); - berry::IPreferencesService::Pointer GetPreferencesService(); + berry::IPreferencesService* GetPreferencesService(); /** * Sets default StateMachine to EventMapper. */ void start(ctkPluginContext* context); void stop(ctkPluginContext* context); private: static QmitkCommonActivator* m_Instance; static ctkPluginContext* m_Context; QScopedPointer m_ViewCoordinator; QScopedPointer > m_PrefServiceTracker; }; #endif /* QMITKCOMMONACTIVATOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp index 5b4a711171..c08a3fbb1e 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp @@ -1,29 +1,30 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkActionBarAdvisor.h" +#include -QmitkActionBarAdvisor::QmitkActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) +QmitkActionBarAdvisor::QmitkActionBarAdvisor(const berry::IActionBarConfigurer::Pointer& configurer) : berry::ActionBarAdvisor(configurer) { } -void QmitkActionBarAdvisor::FillMenuBar(void* ) +void QmitkActionBarAdvisor::FillMenuBar(berry::IMenuManager* ) { } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h index d6293ad90c..e091a41664 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h @@ -1,34 +1,34 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKACTIONBARADVISOR_H_ #define QMITKACTIONBARADVISOR_H_ #include class QmitkActionBarAdvisor : public berry::ActionBarAdvisor { public: - QmitkActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer); + QmitkActionBarAdvisor(const berry::SmartPointer& configurer); protected: - void FillMenuBar(void* menuBar); + void FillMenuBar(berry::IMenuManager* menuBar); }; #endif /*QMITKACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp index a73348a1f0..610202e788 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp @@ -1,45 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkWorkbenchAdvisor.h" #include #include "QmitkWorkbenchWindowAdvisor.h" -const std::string QmitkWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.coreapp.defaultperspective"; +const QString QmitkWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.coreapp.defaultperspective"; void QmitkWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { return new QmitkWorkbenchWindowAdvisor(configurer); } -std::string QmitkWorkbenchAdvisor::GetInitialWindowPerspectiveId() +QString QmitkWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h index 49ffbdf4e1..44578ae9a3 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h @@ -1,45 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKWORKBENCHADVISOR_H_ #define QMITKWORKBENCHADVISOR_H_ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include class QmitkWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string DEFAULT_PERSPECTIVE_ID; // = org.mitk.coreapp.defaultperspective + static const QString DEFAULT_PERSPECTIVE_ID; // = org.mitk.coreapp.defaultperspective void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); - std::string GetInitialWindowPerspectiveId(); + QString GetInitialWindowPerspectiveId(); }; #endif /*QMITKWORKBENCHADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp index 87798b6ccd..72e466f953 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp @@ -1,120 +1,119 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkWorkbenchWindowAdvisor.h" #include "QmitkActionBarAdvisor.h" #include #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include #include QmitkWorkbenchWindowAdvisor::QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) , dropTargetListener(new QmitkDefaultDropTargetListener) { } berry::ActionBarAdvisor::Pointer QmitkWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkActionBarAdvisor(configurer)); return actionBarAdvisor; } void QmitkWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast(window->GetShell()->GetControl()); QMenuBar* menuBar = mainWindow->menuBar(); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->addAction(new QmitkFileOpenAction(window)); fileMenu->addSeparator(); fileMenu->addAction(new QmitkFileExitAction(window)); berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); - const std::vector& viewDescriptors = viewRegistry->GetViews(); + QList viewDescriptors = viewRegistry->GetViews(); QMenu* viewMenu = menuBar->addMenu("Show &View"); // sort elements (converting vector to map...) - std::vector::const_iterator iter; - std::map VDMap; + std::map VDMap; - for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) + for (auto iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; - std::pair p((*iter)->GetLabel(), (*iter)); + std::pair p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } QToolBar* qToolbar = new QToolBar; - std::map::const_iterator MapIter; - for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) + for (auto MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); //m_ViewActions.push_back(viewAction); viewMenu->addAction(viewAction); qToolbar->addAction(viewAction); } mainWindow->addToolBar(qToolbar); QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); mainWindow->setStatusBar(qStatusBar); QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } void QmitkWorkbenchWindowAdvisor::PreWindowOpen() { this->GetWindowConfigurer()->AddEditorAreaTransfer(QStringList("text/uri-list")); - this->GetWindowConfigurer()->ConfigureEditorAreaDropListener(dropTargetListener); + this->GetWindowConfigurer()->ConfigureEditorAreaDropListener(dropTargetListener.data()); } diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h index d075cf3aaf..47e76a3217 100644 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h +++ b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h @@ -1,41 +1,42 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKWORKBENCHWINDOWADVISOR_H_ #define QMITKWORKBENCHWINDOWADVISOR_H_ #include +#include class QmitkWorkbenchWindowAdvisor : public berry::WorkbenchWindowAdvisor { public: - QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer); + QmitkWorkbenchWindowAdvisor(berry::SmartPointer configurer); - berry::ActionBarAdvisor::Pointer CreateActionBarAdvisor( - berry::IActionBarConfigurer::Pointer configurer); + berry::SmartPointer CreateActionBarAdvisor( + berry::SmartPointer configurer); void PostWindowCreate(); void PreWindowOpen(); private: - berry::IDropTargetListener::Pointer dropTargetListener; + QScopedPointer dropTargetListener; }; #endif /*QMITKWORKBENCHWINDOWADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp index fdb7175c07..cfac1b80bd 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp @@ -1,1054 +1,1054 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDataManagerView.h" #include //# Own Includes //## mitk #include "mitkDataStorageEditorInput.h" #include "mitkIDataStorageReference.h" #include "mitkNodePredicateDataType.h" #include "mitkCoreObjectFactory.h" #include "mitkColorProperty.h" #include "mitkCommon.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateProperty.h" #include "mitkEnumerationProperty.h" #include "mitkLookupTableProperty.h" #include "mitkProperties.h" #include #include #include #include #include //## Qmitk #include #include #include #include #include #include #include #include "src/internal/QmitkNodeTableViewKeyFilter.h" #include "src/internal/QmitkInfoDialog.h" #include "src/internal/QmitkDataManagerItemDelegate.h" //## Berry #include #include #include #include #include #include //# Toolkit Includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkDataNodeObject.h" #include "mitkIContextMenuAction.h" #include "berryIExtensionRegistry.h" #include "mitkRenderingModeProperty.h" const QString QmitkDataManagerView::VIEW_ID = "org.mitk.views.datamanager"; QmitkDataManagerView::QmitkDataManagerView() : m_GlobalReinitOnNodeDelete(true), m_ItemDelegate(NULL) { } QmitkDataManagerView::~QmitkDataManagerView() { //Remove all registered actions from each descriptor for (std::vector< std::pair< QmitkNodeDescriptor*, QAction* > >::iterator it = m_DescriptorActionList.begin();it != m_DescriptorActionList.end(); it++) { // first== the NodeDescriptor; second== the registered QAction (it->first)->RemoveAction(it->second); } } void QmitkDataManagerView::CreateQtPartControl(QWidget* parent) { m_CurrentRowCount = 0; m_Parent = parent; //# Preferences berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node(VIEW_ID)) .Cast(); assert( prefs ); prefs->OnChanged.AddListener( berry::MessageDelegate1( this , &QmitkDataManagerView::OnPreferencesChanged ) ); //# GUI m_NodeTreeModel = new QmitkDataStorageTreeModel(this->GetDataStorage()); m_NodeTreeModel->setParent( parent ); m_NodeTreeModel->SetPlaceNewNodesOnTop( prefs->GetBool("Place new nodes on top", true) ); m_SurfaceDecimation = prefs->GetBool("Use surface decimation", false); // Prepare filters m_HelperObjectFilterPredicate = mitk::NodePredicateOr::New( mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true)), mitk::NodePredicateProperty::New("hidden object", mitk::BoolProperty::New(true))); m_NodeWithNoDataFilterPredicate = mitk::NodePredicateData::New(0); m_FilterModel = new QmitkDataStorageFilterProxyModel(); m_FilterModel->setSourceModel(m_NodeTreeModel); m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate); m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate); //# Tree View (experimental) m_NodeTreeView = new QTreeView; m_NodeTreeView->setHeaderHidden(true); m_NodeTreeView->setSelectionMode( QAbstractItemView::ExtendedSelection ); m_NodeTreeView->setSelectionBehavior( QAbstractItemView::SelectRows ); m_NodeTreeView->setAlternatingRowColors(true); m_NodeTreeView->setDragEnabled(true); m_NodeTreeView->setDropIndicatorShown(true); m_NodeTreeView->setAcceptDrops(true); m_NodeTreeView->setContextMenuPolicy(Qt::CustomContextMenu); m_NodeTreeView->setModel(m_FilterModel); m_NodeTreeView->setTextElideMode(Qt::ElideMiddle); m_NodeTreeView->installEventFilter(new QmitkNodeTableViewKeyFilter(this)); m_ItemDelegate = new QmitkDataManagerItemDelegate(m_NodeTreeView); m_NodeTreeView->setItemDelegate(m_ItemDelegate); QObject::connect( m_NodeTreeView, SIGNAL(customContextMenuRequested(const QPoint&)) , this, SLOT(NodeTableViewContextMenuRequested(const QPoint&)) ); QObject::connect( m_NodeTreeModel, SIGNAL(rowsInserted (const QModelIndex&, int, int)) , this, SLOT(NodeTreeViewRowsInserted ( const QModelIndex&, int, int )) ); QObject::connect( m_NodeTreeModel, SIGNAL(rowsRemoved (const QModelIndex&, int, int)) , this, SLOT(NodeTreeViewRowsRemoved( const QModelIndex&, int, int )) ); QObject::connect( m_NodeTreeView->selectionModel() , SIGNAL( selectionChanged ( const QItemSelection &, const QItemSelection & ) ) , this , SLOT( NodeSelectionChanged ( const QItemSelection &, const QItemSelection & ) ) ); //# m_NodeMenu m_NodeMenu = new QMenu(m_NodeTreeView); // # Actions berry::IEditorRegistry* editorRegistry = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); QList editors = editorRegistry->GetEditors("*.mitk"); if (editors.size() > 1) { m_ShowInMapper = new QSignalMapper(this); foreach(berry::IEditorDescriptor::Pointer descriptor, editors) { QAction* action = new QAction(descriptor->GetLabel(), this); m_ShowInActions << action; m_ShowInMapper->connect(action, SIGNAL(triggered()), m_ShowInMapper, SLOT(map())); m_ShowInMapper->setMapping(action, descriptor->GetId()); } connect(m_ShowInMapper, SIGNAL(mapped(QString)), this, SLOT(ShowIn(QString))); } QmitkNodeDescriptor* unknownDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetUnknownDataNodeDescriptor(); QmitkNodeDescriptor* imageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image"); QmitkNodeDescriptor* diffusionImageDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("DiffusionImage"); QmitkNodeDescriptor* surfaceDataNodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Surface"); QAction* globalReinitAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"), "Global Reinit", this); QObject::connect( globalReinitAction, SIGNAL( triggered(bool) ) , this, SLOT( GlobalReinit(bool) ) ); unknownDataNodeDescriptor->AddAction(globalReinitAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor, globalReinitAction)); QAction* saveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.datamanager/Save_48.png"), this->GetSite()->GetWorkbenchWindow()); unknownDataNodeDescriptor->AddAction(saveAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,saveAction)); QAction* removeAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Remove_48.png"), "Remove", this); QObject::connect( removeAction, SIGNAL( triggered(bool) ) , this, SLOT( RemoveSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(removeAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,removeAction)); QAction* reinitAction = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"), "Reinit", this); QObject::connect( reinitAction, SIGNAL( triggered(bool) ) , this, SLOT( ReinitSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(reinitAction); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,reinitAction)); // find contextMenuAction extension points and add them to the node descriptor berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); QList cmActions( extensionPointService->GetConfigurationElementsFor("org.mitk.gui.qt.datamanager.contextMenuActions") ); QList::iterator cmActionsIt; QmitkNodeDescriptor* tmpDescriptor; QAction* contextMenuAction; QVariant cmActionDataIt; m_ConfElements.clear(); int i=1; for (cmActionsIt = cmActions.begin() ; cmActionsIt != cmActions.end() ; ++cmActionsIt) { QString cmNodeDescriptorName = (*cmActionsIt)->GetAttribute("nodeDescriptorName"); QString cmLabel = (*cmActionsIt)->GetAttribute("label"); QString cmClass = (*cmActionsIt)->GetAttribute("class"); if(!cmNodeDescriptorName.isEmpty() && !cmLabel.isEmpty() && !cmClass.isEmpty()) { QString cmIcon = (*cmActionsIt)->GetAttribute("icon"); // create context menu entry here tmpDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(cmNodeDescriptorName); if(!tmpDescriptor) { MITK_WARN << "cannot add action \"" << cmLabel << "\" because descriptor " << cmNodeDescriptorName << " does not exist"; continue; } // check if the user specified an icon attribute if ( !cmIcon.isEmpty() ) { - contextMenuAction = new QAction( QIcon(cmIco), cmLabel, parent); + contextMenuAction = new QAction( QIcon(cmIcon), cmLabel, parent); } else { contextMenuAction = new QAction( cmLabel, parent); } tmpDescriptor->AddAction(contextMenuAction); m_DescriptorActionList.push_back(std::pair(tmpDescriptor,contextMenuAction)); m_ConfElements[contextMenuAction] = *cmActionsIt; cmActionDataIt.setValue(i); contextMenuAction->setData( cmActionDataIt ); connect( contextMenuAction, SIGNAL( triggered(bool) ) , this, SLOT( ContextMenuActionTriggered(bool) ) ); ++i; } } m_OpacitySlider = new QSlider; m_OpacitySlider->setMinimum(0); m_OpacitySlider->setMaximum(100); m_OpacitySlider->setOrientation(Qt::Horizontal); QObject::connect( m_OpacitySlider, SIGNAL( valueChanged(int) ) , this, SLOT( OpacityChanged(int) ) ); QLabel* _OpacityLabel = new QLabel("Opacity: "); QHBoxLayout* _OpacityWidgetLayout = new QHBoxLayout; _OpacityWidgetLayout->setContentsMargins(4,4,4,4); _OpacityWidgetLayout->addWidget(_OpacityLabel); _OpacityWidgetLayout->addWidget(m_OpacitySlider); QWidget* _OpacityWidget = new QWidget; _OpacityWidget->setLayout(_OpacityWidgetLayout); QWidgetAction* opacityAction = new QWidgetAction(this); opacityAction ->setDefaultWidget(_OpacityWidget); QObject::connect( opacityAction , SIGNAL( changed() ) , this, SLOT( OpacityActionChanged() ) ); unknownDataNodeDescriptor->AddAction(opacityAction , false); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,opacityAction)); m_ColorButton = new QPushButton; m_ColorButton->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); //m_ColorButton->setText("Change color"); QObject::connect( m_ColorButton, SIGNAL( clicked() ) , this, SLOT( ColorChanged() ) ); QLabel* _ColorLabel = new QLabel("Color: "); _ColorLabel->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QHBoxLayout* _ColorWidgetLayout = new QHBoxLayout; _ColorWidgetLayout->setContentsMargins(4,4,4,4); _ColorWidgetLayout->addWidget(_ColorLabel); _ColorWidgetLayout->addWidget(m_ColorButton); QWidget* _ColorWidget = new QWidget; _ColorWidget->setLayout(_ColorWidgetLayout); QWidgetAction* colorAction = new QWidgetAction(this); colorAction->setDefaultWidget(_ColorWidget); QObject::connect( colorAction, SIGNAL( changed() ) , this, SLOT( ColorActionChanged() ) ); unknownDataNodeDescriptor->AddAction(colorAction, false); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,colorAction)); m_ComponentSlider = new QmitkNumberPropertySlider; m_ComponentSlider->setOrientation(Qt::Horizontal); //QObject::connect( m_OpacitySlider, SIGNAL( valueChanged(int) ) // , this, SLOT( OpacityChanged(int) ) ); QLabel* _ComponentLabel = new QLabel("Component: "); QHBoxLayout* _ComponentWidgetLayout = new QHBoxLayout; _ComponentWidgetLayout->setContentsMargins(4,4,4,4); _ComponentWidgetLayout->addWidget(_ComponentLabel); _ComponentWidgetLayout->addWidget(m_ComponentSlider); QLabel* _ComponentValueLabel = new QLabel(); _ComponentWidgetLayout->addWidget(_ComponentValueLabel); connect(m_ComponentSlider, SIGNAL(valueChanged(int)), _ComponentValueLabel, SLOT(setNum(int))); QWidget* _ComponentWidget = new QWidget; _ComponentWidget->setLayout(_ComponentWidgetLayout); QWidgetAction* componentAction = new QWidgetAction(this); componentAction->setDefaultWidget(_ComponentWidget); QObject::connect( componentAction , SIGNAL( changed() ) , this, SLOT( ComponentActionChanged() ) ); imageDataNodeDescriptor->AddAction(componentAction, false); m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor,componentAction)); if (diffusionImageDataNodeDescriptor!=NULL) { diffusionImageDataNodeDescriptor->AddAction(componentAction, false); m_DescriptorActionList.push_back(std::pair(diffusionImageDataNodeDescriptor,componentAction)); } m_TextureInterpolation = new QAction("Texture Interpolation", this); m_TextureInterpolation->setCheckable ( true ); QObject::connect( m_TextureInterpolation, SIGNAL( changed() ) , this, SLOT( TextureInterpolationChanged() ) ); QObject::connect( m_TextureInterpolation, SIGNAL( toggled(bool) ) , this, SLOT( TextureInterpolationToggled(bool) ) ); imageDataNodeDescriptor->AddAction(m_TextureInterpolation, false); m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor,m_TextureInterpolation)); if (diffusionImageDataNodeDescriptor!=NULL) { diffusionImageDataNodeDescriptor->AddAction(m_TextureInterpolation, false); m_DescriptorActionList.push_back(std::pair(diffusionImageDataNodeDescriptor,m_TextureInterpolation)); } m_ColormapAction = new QAction("Colormap", this); m_ColormapAction->setMenu(new QMenu); QObject::connect( m_ColormapAction->menu(), SIGNAL( aboutToShow() ) , this, SLOT( ColormapMenuAboutToShow() ) ); imageDataNodeDescriptor->AddAction(m_ColormapAction, false); m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor, m_ColormapAction)); if (diffusionImageDataNodeDescriptor!=NULL) { diffusionImageDataNodeDescriptor->AddAction(m_ColormapAction, false); m_DescriptorActionList.push_back(std::pair(diffusionImageDataNodeDescriptor, m_ColormapAction)); } m_SurfaceRepresentation = new QAction("Surface Representation", this); m_SurfaceRepresentation->setMenu(new QMenu(m_NodeTreeView)); QObject::connect( m_SurfaceRepresentation->menu(), SIGNAL( aboutToShow() ) , this, SLOT( SurfaceRepresentationMenuAboutToShow() ) ); surfaceDataNodeDescriptor->AddAction(m_SurfaceRepresentation, false); m_DescriptorActionList.push_back(std::pair(surfaceDataNodeDescriptor, m_SurfaceRepresentation)); QAction* showOnlySelectedNodes = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/ShowSelectedNode_48.png") , "Show only selected nodes", this); QObject::connect( showOnlySelectedNodes, SIGNAL( triggered(bool) ) , this, SLOT( ShowOnlySelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(showOnlySelectedNodes); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor, showOnlySelectedNodes)); QAction* toggleSelectedVisibility = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/InvertShowSelectedNode_48.png") , "Toggle visibility", this); QObject::connect( toggleSelectedVisibility, SIGNAL( triggered(bool) ) , this, SLOT( ToggleVisibilityOfSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(toggleSelectedVisibility); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,toggleSelectedVisibility)); QAction* actionShowInfoDialog = new QAction(QIcon(":/org.mitk.gui.qt.datamanager/ShowDataInfo_48.png") , "Details...", this); QObject::connect( actionShowInfoDialog, SIGNAL( triggered(bool) ) , this, SLOT( ShowInfoDialogForSelectedNodes(bool) ) ); unknownDataNodeDescriptor->AddAction(actionShowInfoDialog); m_DescriptorActionList.push_back(std::pair(unknownDataNodeDescriptor,actionShowInfoDialog)); //obsolete... //QAction* otsuFilterAction = new QAction("Apply Otsu Filter", this); //QObject::connect( otsuFilterAction, SIGNAL( triggered(bool) ) // , this, SLOT( OtsuFilter(bool) ) ); // //Otsu filter does not work properly, remove it temporarily // imageDataNodeDescriptor->AddAction(otsuFilterAction); // m_DescriptorActionList.push_back(std::pair(imageDataNodeDescriptor,otsuFilterAction)); QGridLayout* _DndFrameWidgetLayout = new QGridLayout; _DndFrameWidgetLayout->addWidget(m_NodeTreeView, 0, 0); _DndFrameWidgetLayout->setContentsMargins(0,0,0,0); m_DndFrameWidget = new QmitkDnDFrameWidget(m_Parent); m_DndFrameWidget->setLayout(_DndFrameWidgetLayout); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_Parent->setLayout(layout); } void QmitkDataManagerView::SetFocus() { } void QmitkDataManagerView::ContextMenuActionTriggered( bool ) { QAction* action = qobject_cast ( sender() ); std::map::iterator it = m_ConfElements.find( action ); if( it == m_ConfElements.end() ) { MITK_WARN << "associated conf element for action " << action->text().toStdString() << " not found"; return; } berry::IConfigurationElement::Pointer confElem = it->second; mitk::IContextMenuAction* contextMenuAction = confElem->CreateExecutableExtension("class"); QString className = confElem->GetAttribute("class"); QString smoothed = confElem->GetAttribute("smoothed"); if(className == "QmitkCreatePolygonModelAction") { contextMenuAction->SetDataStorage(this->GetDataStorage()); if(smoothed == "false") { contextMenuAction->SetSmoothed(false); } else { contextMenuAction->SetSmoothed(true); } contextMenuAction->SetDecimated(m_SurfaceDecimation); } else if(className == "QmitkStatisticsAction") { contextMenuAction->SetFunctionality(this); } else if(className == "QmitkCreateSimulationAction") { contextMenuAction->SetDataStorage(this->GetDataStorage()); } contextMenuAction->Run( this->GetCurrentSelection() ); // run the action } void QmitkDataManagerView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { if( m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() != prefs->GetBool("Place new nodes on top", true) ) m_NodeTreeModel->SetPlaceNewNodesOnTop( !m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() ); bool hideHelperObjects = !prefs->GetBool("Show helper objects", false); if (m_FilterModel->HasFilterPredicate(m_HelperObjectFilterPredicate) != hideHelperObjects) { if (hideHelperObjects) { m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate); } else { m_FilterModel->RemoveFilterPredicate(m_HelperObjectFilterPredicate); } } bool hideNodesWithNoData = !prefs->GetBool("Show nodes containing no data", false); if (m_FilterModel->HasFilterPredicate(m_NodeWithNoDataFilterPredicate) != hideNodesWithNoData) { if (hideNodesWithNoData) { m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate); } else { m_FilterModel->RemoveFilterPredicate(m_NodeWithNoDataFilterPredicate); } } m_GlobalReinitOnNodeDelete = prefs->GetBool("Call global reinit if node is deleted", true); m_NodeTreeView->expandAll(); m_SurfaceDecimation = prefs->GetBool("Use surface decimation", false); this->GlobalReinit(); } void QmitkDataManagerView::NodeTableViewContextMenuRequested( const QPoint & pos ) { QModelIndex selectedProxy = m_NodeTreeView->indexAt ( pos ); QModelIndex selected = m_FilterModel->mapToSource(selectedProxy); mitk::DataNode::Pointer node = m_NodeTreeModel->GetNode(selected); QList selectedNodes = this->GetCurrentSelection(); if(!selectedNodes.isEmpty()) { m_NodeMenu->clear(); QList actions; if(selectedNodes.size() == 1 ) { actions = QmitkNodeDescriptorManager::GetInstance()->GetActions(node); for(QList::iterator it = actions.begin(); it != actions.end(); ++it) { (*it)->setData(QVariant::fromValue(node.GetPointer())); } } else actions = QmitkNodeDescriptorManager::GetInstance()->GetActions(selectedNodes); if (!m_ShowInActions.isEmpty()) { QMenu* showInMenu = m_NodeMenu->addMenu("Show In"); showInMenu->addActions(m_ShowInActions); } m_NodeMenu->addActions(actions); m_NodeMenu->popup(QCursor::pos()); } } void QmitkDataManagerView::OpacityChanged(int value) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { float opacity = static_cast(value)/100.0f; node->SetFloatProperty("opacity", opacity); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::OpacityActionChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { float opacity = 0.0; if(node->GetFloatProperty("opacity", opacity)) { m_OpacitySlider->setValue(static_cast(opacity*100)); } } } void QmitkDataManagerView::ComponentActionChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); mitk::IntProperty* componentProperty = NULL; int numComponents = 0; if(node) { componentProperty = dynamic_cast(node->GetProperty("Image.Displayed Component")); mitk::Image* img = dynamic_cast(node->GetData()); if (img != NULL) { numComponents = img->GetPixelType().GetNumberOfComponents(); } } if (componentProperty && numComponents > 1) { m_ComponentSlider->SetProperty(componentProperty); m_ComponentSlider->setMinValue(0); m_ComponentSlider->setMaxValue(numComponents-1); } else { m_ComponentSlider->SetProperty(static_cast(NULL)); } } void QmitkDataManagerView::ColorChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { mitk::Color color; mitk::ColorProperty::Pointer colorProp; node->GetProperty(colorProp,"color"); if(colorProp.IsNull()) return; color = colorProp->GetValue(); QColor initial(color.GetRed()*255,color.GetGreen()*255,color.GetBlue()*255); QColor qcolor = QColorDialog::getColor(initial,0,QString("Change color")); if (!qcolor.isValid()) return; m_ColorButton->setAutoFillBackground(true); node->SetProperty("color",mitk::ColorProperty::New(qcolor.red()/255.0,qcolor.green()/255.0,qcolor.blue()/255.0)); if (node->GetProperty("binaryimage.selectedcolor")) { node->SetProperty("binaryimage.selectedcolor",mitk::ColorProperty::New(qcolor.red()/255.0,qcolor.green()/255.0,qcolor.blue()/255.0)); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::ColorActionChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { mitk::Color color; mitk::ColorProperty::Pointer colorProp; node->GetProperty(colorProp,"color"); if(colorProp.IsNull()) return; color = colorProp->GetValue(); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255)); styleSheet.append(")"); m_ColorButton->setStyleSheet(styleSheet); } } void QmitkDataManagerView::TextureInterpolationChanged() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { bool textureInterpolation = false; node->GetBoolProperty("texture interpolation", textureInterpolation); m_TextureInterpolation->setChecked(textureInterpolation); } } void QmitkDataManagerView::TextureInterpolationToggled( bool checked ) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(node) { node->SetBoolProperty("texture interpolation", checked); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkDataManagerView::ColormapActionToggled( bool /*checked*/ ) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(!node) return; mitk::LookupTableProperty::Pointer lookupTableProperty = dynamic_cast(node->GetProperty("LookupTable")); if (!lookupTableProperty) return; QAction* senderAction = qobject_cast(QObject::sender()); if(!senderAction) return; std::string activatedItem = senderAction->text().toStdString(); mitk::LookupTable::Pointer lookupTable = lookupTableProperty->GetValue(); if (!lookupTable) return; lookupTable->SetType(activatedItem); lookupTableProperty->SetValue(lookupTable); mitk::RenderingModeProperty::Pointer renderingMode = dynamic_cast(node->GetProperty("Image Rendering.Mode")); renderingMode->SetValue(mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ColormapMenuAboutToShow() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(!node) return; mitk::LookupTableProperty::Pointer lookupTableProperty = dynamic_cast(node->GetProperty("LookupTable")); if (!lookupTableProperty) { mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); lookupTableProperty = mitk::LookupTableProperty::New(); lookupTableProperty->SetLookupTable(mitkLut); node->SetProperty("LookupTable", lookupTableProperty); } mitk::LookupTable::Pointer lookupTable = lookupTableProperty->GetValue(); if (!lookupTable) return; m_ColormapAction->menu()->clear(); QAction* tmp; int i = 0; std::string lutType = lookupTable->typenameList[i]; while (lutType != "END_OF_ARRAY") { tmp = m_ColormapAction->menu()->addAction(QString::fromStdString(lutType)); tmp->setCheckable(true); if (lutType == lookupTable->GetActiveTypeAsString()) { tmp->setChecked(true); } QObject::connect(tmp, SIGNAL(triggered(bool)), this, SLOT(ColormapActionToggled(bool))); lutType = lookupTable->typenameList[++i]; } } void QmitkDataManagerView::SurfaceRepresentationMenuAboutToShow() { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(!node) return; mitk::EnumerationProperty* representationProp = dynamic_cast (node->GetProperty("material.representation")); if(!representationProp) return; // clear menu m_SurfaceRepresentation->menu()->clear(); QAction* tmp; // create menu entries for(mitk::EnumerationProperty::EnumConstIterator it=representationProp->Begin(); it!=representationProp->End() ; it++) { tmp = m_SurfaceRepresentation->menu()->addAction(QString::fromStdString(it->second)); tmp->setCheckable(true); if(it->second == representationProp->GetValueAsString()) { tmp->setChecked(true); } QObject::connect( tmp, SIGNAL( triggered(bool) ) , this, SLOT( SurfaceRepresentationActionToggled(bool) ) ); } } void QmitkDataManagerView::SurfaceRepresentationActionToggled( bool /*checked*/ ) { mitk::DataNode* node = m_NodeTreeModel->GetNode(m_FilterModel->mapToSource(m_NodeTreeView->selectionModel()->currentIndex())); if(!node) return; mitk::EnumerationProperty* representationProp = dynamic_cast (node->GetProperty("material.representation")); if(!representationProp) return; QAction* senderAction = qobject_cast ( QObject::sender() ); if(!senderAction) return; std::string activatedItem = senderAction->text().toStdString(); if ( activatedItem != representationProp->GetValueAsString() ) { if ( representationProp->IsValidEnumerationValue( activatedItem ) ) { representationProp->SetValue( activatedItem ); representationProp->InvokeEvent( itk::ModifiedEvent() ); representationProp->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkDataManagerView::ReinitSelectedNodes( bool ) { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow == NULL) renderWindow = this->OpenRenderWindowPart(false); QList selectedNodes = this->GetCurrentSelection(); foreach(mitk::DataNode::Pointer node, selectedNodes) { mitk::BaseData::Pointer basedata = node->GetData(); if ( basedata.IsNotNull() && basedata->GetTimeGeometry()->IsValid() ) { renderWindow->GetRenderingManager()->InitializeViews( basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); renderWindow->GetRenderingManager()->RequestUpdateAll(); } } } void QmitkDataManagerView::RemoveSelectedNodes( bool ) { QModelIndexList indexesOfSelectedRowsFiltered = m_NodeTreeView->selectionModel()->selectedRows(); QModelIndexList indexesOfSelectedRows; for (int i = 0; i < indexesOfSelectedRowsFiltered.size(); ++i) { indexesOfSelectedRows.push_back(m_FilterModel->mapToSource(indexesOfSelectedRowsFiltered[i])); } if(indexesOfSelectedRows.size() < 1) { return; } std::vector selectedNodes; mitk::DataNode* node = 0; QString question = tr("Do you really want to remove "); for (QModelIndexList::iterator it = indexesOfSelectedRows.begin() ; it != indexesOfSelectedRows.end(); it++) { node = m_NodeTreeModel->GetNode(*it); // if node is not defined or if the node contains geometry data do not remove it if ( node != 0 /*& strcmp(node->GetData()->GetNameOfClass(), "PlaneGeometryData") != 0*/ ) { selectedNodes.push_back(node); question.append(QString::fromStdString(node->GetName())); question.append(", "); } } // remove the last two characters = ", " question = question.remove(question.size()-2, 2); question.append(" from data storage?"); QMessageBox::StandardButton answerButton = QMessageBox::question( m_Parent , tr("DataManager") , question , QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(answerButton == QMessageBox::Yes) { for (std::vector::iterator it = selectedNodes.begin() ; it != selectedNodes.end(); it++) { node = *it; this->GetDataStorage()->Remove(node); if (m_GlobalReinitOnNodeDelete) this->GlobalReinit(false); } } } void QmitkDataManagerView::MakeAllNodesInvisible( bool ) { QList nodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, nodes) { node->SetVisibility(false); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowOnlySelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); QList allNodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, allNodes) { node->SetVisibility(selectedNodes.contains(node)); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ToggleVisibilityOfSelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); bool isVisible = false; foreach(mitk::DataNode::Pointer node, selectedNodes) { isVisible = false; node->GetBoolProperty("visible", isVisible); node->SetVisibility(!isVisible); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowInfoDialogForSelectedNodes( bool ) { QList selectedNodes = this->GetCurrentSelection(); QmitkInfoDialog _QmitkInfoDialog(selectedNodes, this->m_Parent); _QmitkInfoDialog.exec(); } void QmitkDataManagerView::NodeChanged(const mitk::DataNode* /*node*/) { // m_FilterModel->invalidate(); // fix as proposed by R. Khlebnikov in the mitk-users mail from 02.09.2014 QMetaObject::invokeMethod( m_FilterModel, "invalidate", Qt::QueuedConnection ); } QItemSelectionModel *QmitkDataManagerView::GetDataNodeSelectionModel() const { return m_NodeTreeView->selectionModel(); } void QmitkDataManagerView::GlobalReinit( bool ) { mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart(); if (renderWindow == NULL) renderWindow = this->OpenRenderWindowPart(false); // no render window available if (renderWindow == NULL) return; mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); } void QmitkDataManagerView::OtsuFilter( bool ) { QList selectedNodes = this->GetCurrentSelection(); mitk::Image::Pointer mitkImage = 0; foreach(mitk::DataNode::Pointer node, selectedNodes) { mitkImage = dynamic_cast( node->GetData() ); if(mitkImage.IsNull()) continue; try { // get selected mitk image const unsigned short dim = 3; typedef short InputPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, dim > InputImageType; typedef itk::Image< OutputPixelType, dim > OutputImageType; typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetOutsideValue( 1 ); filter->SetInsideValue( 0 ); InputImageType::Pointer itkImage; mitk::CastToItkImage(mitkImage, itkImage); filter->SetInput( itkImage ); filter->Update(); mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); std::string nameOfResultImage = node->GetName(); nameOfResultImage.append("Otsu"); resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); resultNode->SetData( mitk::ImportItkImage(filter->GetOutput())->Clone()); this->GetDataStorage()->Add(resultNode, node); } catch( std::exception& err ) { MITK_ERROR(qPrintable(this->GetClassName())) << err.what(); } } } void QmitkDataManagerView::NodeTreeViewRowsRemoved ( const QModelIndex & /*parent*/, int /*start*/, int /*end*/ ) { m_CurrentRowCount = m_NodeTreeModel->rowCount(); } void QmitkDataManagerView::NodeTreeViewRowsInserted( const QModelIndex & parent, int, int ) { m_NodeTreeView->setExpanded(parent, true); // a new row was inserted if( m_CurrentRowCount == 0 && m_NodeTreeModel->rowCount() == 1 ) { this->OpenRenderWindowPart(); m_CurrentRowCount = m_NodeTreeModel->rowCount(); } } void QmitkDataManagerView::NodeSelectionChanged( const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/ ) { QList nodes = m_NodeTreeModel->GetNodeSet(); foreach(mitk::DataNode::Pointer node, nodes) { if ( node.IsNotNull() ) node->SetBoolProperty("selected", false); } nodes.clear(); nodes = this->GetCurrentSelection(); foreach(mitk::DataNode::Pointer node, nodes) { if ( node.IsNotNull() ) node->SetBoolProperty("selected", true); } //changing the selection does NOT require any rendering processes! //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDataManagerView::ShowIn(const QString &editorId) { berry::IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); berry::IEditorInput::Pointer input(new mitk::DataStorageEditorInput(this->GetDataStorageReference())); page->OpenEditor(input, editorId, false, berry::IWorkbenchPage::MATCH_ID); } mitk::IRenderWindowPart* QmitkDataManagerView::OpenRenderWindowPart(bool activatedEditor) { if (activatedEditor) { return this->GetRenderWindowPart(QmitkAbstractView::ACTIVATE | QmitkAbstractView::OPEN); } else { return this->GetRenderWindowPart(QmitkAbstractView::BRING_TO_FRONT | QmitkAbstractView::OPEN); } } diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp index c5f3c48f00..fa6fb7f330 100644 --- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp +++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp @@ -1,91 +1,92 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkNodeTableViewKeyFilter.h" #include #include #include "../QmitkDataManagerView.h" #include "berryIPreferencesService.h" +#include "berryPlatform.h" QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter( QObject* _DataManagerView ) : QObject(_DataManagerView) { m_PreferencesService = berry::Platform::GetPreferencesService(); } bool QmitkNodeTableViewKeyFilter::eventFilter( QObject *obj, QEvent *event ) { QmitkDataManagerView* _DataManagerView = qobject_cast(this->parent()); if (event->type() == QEvent::KeyPress && _DataManagerView) { berry::IPreferences::Pointer nodeTableKeyPrefs = m_PreferencesService->GetSystemPreferences()->Node("/DataManager/Hotkeys"); QKeySequence _MakeAllInvisible = QKeySequence(nodeTableKeyPrefs->Get("Make all nodes invisible", "Ctrl+, V")); QKeySequence _ToggleVisibility = QKeySequence(nodeTableKeyPrefs->Get("Toggle visibility of selected nodes", "V")); QKeySequence _DeleteSelectedNodes = QKeySequence(nodeTableKeyPrefs->Get("Delete selected nodes", "Del")); QKeySequence _Reinit = QKeySequence(nodeTableKeyPrefs->Get("Reinit selected nodes", "R")); QKeySequence _GlobalReinit = QKeySequence(nodeTableKeyPrefs->Get("Global Reinit", "Ctrl+, R")); QKeySequence _ShowInfo = QKeySequence(nodeTableKeyPrefs->Get("Show Node Information", "Ctrl+, I")); QKeyEvent *keyEvent = static_cast(event); QKeySequence _KeySequence = QKeySequence(keyEvent->modifiers(), keyEvent->key()); // if no modifier was pressed the sequence is now empty if(_KeySequence.isEmpty()) _KeySequence = QKeySequence(keyEvent->key()); if(_KeySequence == _MakeAllInvisible) { // trigger deletion of selected node(s) _DataManagerView->MakeAllNodesInvisible(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _DeleteSelectedNodes) { // trigger deletion of selected node(s) _DataManagerView->RemoveSelectedNodes(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _ToggleVisibility) { // trigger deletion of selected node(s) _DataManagerView->ToggleVisibilityOfSelectedNodes(true); // return true: this means the delete key event is not send to the table return true; } else if(_KeySequence == _Reinit) { _DataManagerView->ReinitSelectedNodes(true); return true; } else if(_KeySequence == _GlobalReinit) { _DataManagerView->GlobalReinit(true); return true; } else if(_KeySequence == _ShowInfo) { _DataManagerView->ShowInfoDialogForSelectedNodes(true); return true; } } // standard event processing return QObject::eventFilter(obj, event); } diff --git a/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomBrowser.cpp b/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomBrowser.cpp index d1813888b9..fbfa7ccff2 100644 --- a/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomBrowser.cpp +++ b/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomBrowser.cpp @@ -1,206 +1,202 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkDicomBrowser.h" #include "mitkPluginActivator.h" #include "berryIQtPreferencePage.h" #include #include #include #include const std::string QmitkDicomBrowser::EDITOR_ID = "org.mitk.editors.dicombrowser"; const QString QmitkDicomBrowser::TEMP_DICOM_FOLDER_SUFFIX="TmpDicomFolder"; QmitkDicomBrowser::QmitkDicomBrowser() : m_Thread(new QThread()) , m_DicomDirectoryListener(new QmitkDicomDirectoryListener()) , m_StoreSCPLauncher(new QmitkStoreSCPLauncher(&m_Builder)) , m_Publisher(new QmitkDicomDataEventPublisher()) { } QmitkDicomBrowser::~QmitkDicomBrowser() { m_Thread.quit(); m_Thread.wait(1000); delete m_DicomDirectoryListener; delete m_StoreSCPLauncher; delete m_Handler; delete m_Publisher; } void QmitkDicomBrowser::CreateQtPartControl(QWidget *parent ) { m_Controls.setupUi( parent ); m_Controls.StoreSCPStatusLabel->setTextFormat(Qt::RichText); m_Controls.StoreSCPStatusLabel->setText(""); TestHandler(); OnPreferencesChanged(0); CreateTemporaryDirectory(); StartDicomDirectoryListener(); m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(false); connect(m_Controls.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int))); connect(m_Controls.externalDataWidget,SIGNAL(SignalStartDicomImport(const QStringList&)), m_Controls.internalDataWidget,SLOT(OnStartDicomImport(const QStringList&))); connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QHash&)), this,SLOT(OnViewButtonAddToDataManager(const QHash&))); connect(m_Controls.internalDataWidget,SIGNAL(SignalFinishedImport()),this, SLOT(OnDicomImportFinished())); connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QHash&)), this,SLOT(OnViewButtonAddToDataManager(const QHash&))); } void QmitkDicomBrowser::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { this->SetSite(site); this->SetInput(input); } void QmitkDicomBrowser::SetFocus() { } berry::IPartListener::Events::Types QmitkDicomBrowser::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkDicomBrowser::OnTabChanged(int page) { if (page == 2)//Query/Retrieve is selected { QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString(); QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString(); if(!((m_Builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&& (m_Builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0))) { StopStoreSCP(); StartStoreSCP(); } } } void QmitkDicomBrowser::OnDicomImportFinished() { m_Controls.tabWidget->setCurrentIndex(0); } void QmitkDicomBrowser::StartDicomDirectoryListener() { if(!m_Thread.isRunning()) { m_DicomDirectoryListener->SetDicomListenerDirectory(m_TempDirectory); m_DicomDirectoryListener->SetDicomFolderSuffix(TEMP_DICOM_FOLDER_SUFFIX); connect(m_DicomDirectoryListener,SIGNAL(SignalStartDicomImport(const QStringList&)),m_Controls.internalDataWidget,SLOT(OnStartDicomImport(const QStringList&)),Qt::DirectConnection); //connect(m_Controls.internalDataWidget,SIGNAL(SignalFinishedImport()),m_DicomDirectoryListener,SLOT(OnImportFinished()),Qt::DirectConnection); m_DicomDirectoryListener->moveToThread(&m_Thread); m_Thread.start(); } } void QmitkDicomBrowser::TestHandler() { m_Handler = new DicomEventHandler(); m_Handler->SubscribeSlots(); } void QmitkDicomBrowser::OnViewButtonAddToDataManager(QHash eventProperties) { ctkDictionary properties; // properties["PatientName"] = eventProperties["PatientName"]; // properties["StudyUID"] = eventProperties["StudyUID"]; // properties["StudyName"] = eventProperties["StudyName"]; // properties["SeriesUID"] = eventProperties["SeriesUID"]; // properties["SeriesName"] = eventProperties["SeriesName"]; properties["FilesForSeries"] = eventProperties["FilesForSeries"]; m_Publisher->PublishSignals(mitk::PluginActivator::getContext()); m_Publisher->AddSeriesToDataManagerEvent(properties); } void QmitkDicomBrowser::StartStoreSCP() { QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StoragePort"].toString(); QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()["StorageAETitle"].toString(); m_Builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(m_TempDirectory); m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&m_Builder); connect(m_StoreSCPLauncher, SIGNAL(SignalStatusOfStoreSCP(const QString&)), this, SLOT(OnStoreSCPStatusChanged(const QString&))); connect(m_StoreSCPLauncher ,SIGNAL(SignalStartImport(const QStringList&)),m_Controls.internalDataWidget,SLOT(OnStartDicomImport(const QStringList&))); connect(m_StoreSCPLauncher ,SIGNAL(SignalStoreSCPError(const QString&)),m_DicomDirectoryListener,SLOT(OnDicomNetworkError(const QString&)),Qt::DirectConnection); connect(m_StoreSCPLauncher ,SIGNAL(SignalStoreSCPError(const QString&)),this,SLOT(OnDicomNetworkError(const QString&)),Qt::DirectConnection); m_StoreSCPLauncher->StartStoreSCP(); } void QmitkDicomBrowser::OnStoreSCPStatusChanged(const QString& status) { m_Controls.StoreSCPStatusLabel->setText(" "+status); } void QmitkDicomBrowser::OnDicomNetworkError(const QString& status) { m_Controls.StoreSCPStatusLabel->setText(" "+status); } void QmitkDicomBrowser::StopStoreSCP() { delete m_StoreSCPLauncher; } void QmitkDicomBrowser::SetPluginDirectory() { m_PluginDirectory = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); m_PluginDirectory.append("/database"); } void QmitkDicomBrowser::CreateTemporaryDirectory() { QDir tmp; QString tmpPath = QDir::tempPath(); m_TempDirectory.clear(); m_TempDirectory.append(tmpPath); m_TempDirectory.append(QString("/")); m_TempDirectory.append(TEMP_DICOM_FOLDER_SUFFIX); m_TempDirectory.append(QString(".")); m_TempDirectory.append(QTime::currentTime().toString("hhmmsszzz")); m_TempDirectory.append(QString::number(QCoreApplication::applicationPid())); tmp.mkdir(QDir::toNativeSeparators( m_TempDirectory )); } void QmitkDicomBrowser::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { SetPluginDirectory(); - berry::IPreferencesService::Pointer prefService= - berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); - std::string targetPath = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader")->Get("default dicom path", m_PluginDirectory.toStdString()); - - m_DatabaseDirectory.clear(); - m_DatabaseDirectory.append(targetPath.c_str()); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + m_DatabaseDirectory = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader")->Get("default dicom path", m_PluginDirectory); m_Controls.internalDataWidget->SetDatabaseDirectory(m_DatabaseDirectory); -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomPreferencePage.cpp b/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomPreferencePage.cpp index fcde85b65c..34c1a35e59 100644 --- a/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.dicom/src/internal/QmitkDicomPreferencePage.cpp @@ -1,120 +1,119 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDicomPreferencePage.h" #include #include #include #include "mitkPluginActivator.h" #include #include #include #include #include #include #include #include #include #include static QString CreateDefaultPath() { QString path = mitk::PluginActivator::getContext()->getDataFile("").absolutePath(); path.append("/database"); return path; } QmitkDicomPreferencePage::QmitkDicomPreferencePage() : m_MainControl(0) { } QmitkDicomPreferencePage::~QmitkDicomPreferencePage() { } void QmitkDicomPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkDicomPreferencePage::CreateQtControl(QWidget* parent) { - berry::IPreferencesService::Pointer prefService= - berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_DicomPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.dicomreader"); m_MainControl = new QWidget(parent); QFormLayout *formLayout = new QFormLayout; formLayout->setHorizontalSpacing(8); formLayout->setVerticalSpacing(24); QHBoxLayout* displayOptionsLayout = new QHBoxLayout; m_PathEdit = new QLineEdit(m_MainControl); displayOptionsLayout->addWidget(m_PathEdit); m_PathSelect = new QPushButton("Select Path",m_MainControl); displayOptionsLayout->addWidget(m_PathSelect); m_PathDefault = new QPushButton("Default",m_MainControl); displayOptionsLayout->addWidget(m_PathDefault); formLayout->addRow("Local database path:",displayOptionsLayout); m_MainControl->setLayout(formLayout); connect(m_PathDefault, SIGNAL(clicked()), this, SLOT(DefaultButtonPushed())); connect(m_PathSelect, SIGNAL(clicked()), this, SLOT(PathSelectButtonPushed())); this->Update(); } QWidget* QmitkDicomPreferencePage::GetQtControl() const { return m_MainControl; } void QmitkDicomPreferencePage::PerformCancel() { } bool QmitkDicomPreferencePage::PerformOk() { - m_DicomPreferencesNode->Put("default dicom path",m_PathEdit->text().toStdString()); + m_DicomPreferencesNode->Put("default dicom path",m_PathEdit->text()); return true; } void QmitkDicomPreferencePage::Update() { - std::string path = m_DicomPreferencesNode->Get("default dicom path", CreateDefaultPath().toStdString()); - m_PathEdit->setText(path.c_str()); + QString path = m_DicomPreferencesNode->Get("default dicom path", CreateDefaultPath()); + m_PathEdit->setText(path); } void QmitkDicomPreferencePage::DefaultButtonPushed() { m_PathEdit->setText(CreateDefaultPath()); } void QmitkDicomPreferencePage::PathSelectButtonPushed() { QString path = QFileDialog::getExistingDirectory(m_MainControl,"Folder for Dicom directory","dir"); if (!path.isEmpty()) { m_PathEdit->setText(path); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp index a612021ba5..70c55d4280 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppIVIMPerspective.cpp @@ -1,50 +1,50 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDIAppIVIMPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppIVIMPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.ivim"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.ivim"); left->AddView("org.mitk.views.segmentation"); lo = layout->GetViewLayout("org.mitk.views.segmentation"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppSyntheticDataGenerationPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppSyntheticDataGenerationPerspective.cpp index 9c5b8c1f83..f85c776dfa 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppSyntheticDataGenerationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDIAppSyntheticDataGenerationPerspective.cpp @@ -1,51 +1,51 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDIAppSyntheticDataGenerationPerspective.h" #include "berryIViewLayout.h" void QmitkDIAppSyntheticDataGenerationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.fiberfoxview"); left->AddView("org.mitk.views.fieldmapgenerator"); left->AddView("org.mitk.views.segmentation"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionDefaultPerspective.cpp index 6cc83b47ac..cdc4e191fd 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionDefaultPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionDefaultPerspective.cpp @@ -1,43 +1,43 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionDefaultPerspective.h" #include "berryIViewLayout.h" void QmitkDiffusionDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.viewnavigatorview", false, berry::IPageLayout::LEFT, 0.25f, editorArea); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp index 62935f08d7..012663d445 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkDiffusionImagingAppPerspective.cpp @@ -1,46 +1,46 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionImagingAppPerspective.h" #include "berryIViewLayout.h" void QmitkDiffusionImagingAppPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkFiberProcessingPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkFiberProcessingPerspective.cpp index 9dd73fb7b4..a32ba777cd 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkFiberProcessingPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkFiberProcessingPerspective.cpp @@ -1,60 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFiberProcessingPerspective.h" #include "berryIViewLayout.h" QmitkFiberProcessingPerspective::QmitkFiberProcessingPerspective() { } QmitkFiberProcessingPerspective::QmitkFiberProcessingPerspective(const QmitkFiberProcessingPerspective& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } void QmitkFiberProcessingPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.fiberprocessing"); left->AddView("org.mitk.views.fiberquantification"); left->AddView("org.mitk.views.segmentation"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkGibbsTractographyPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkGibbsTractographyPerspective.cpp index 8e8a68dd82..9fee132fe5 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkGibbsTractographyPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkGibbsTractographyPerspective.cpp @@ -1,50 +1,50 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkGibbsTractographyPerspective.h" #include "berryIViewLayout.h" void QmitkGibbsTractographyPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.tensorreconstruction"); left->AddView("org.mitk.views.qballreconstruction"); left->AddView("org.mitk.views.gibbstracking"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkProbabilisticTractographyPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkProbabilisticTractographyPerspective.cpp index 86a6c717b2..cfe799025b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkProbabilisticTractographyPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkProbabilisticTractographyPerspective.cpp @@ -1,50 +1,50 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkProbabilisticTractographyPerspective.h" #include "berryIViewLayout.h" void QmitkProbabilisticTractographyPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.diffusionpreprocessing"); left->AddView("org.mitk.views.segmentation"); left->AddView("org.mitk.views.stochasticfibertracking"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkStreamlineTractographyPerspective.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkStreamlineTractographyPerspective.cpp index 73473985a0..03b705d96e 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkStreamlineTractographyPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/Perspectives/QmitkStreamlineTractographyPerspective.cpp @@ -1,50 +1,50 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkStreamlineTractographyPerspective.h" #include "berryIViewLayout.h" void QmitkStreamlineTractographyPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneViewPlaceholder("org.mitk.views.viewnavigatorview", berry::IPageLayout::LEFT, 0.3f, editorArea, false); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager"); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .7f, "org.mbi.diffusionimaginginternal.leftcontrols", false); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.tensorreconstruction"); left->AddView("org.mitk.views.segmentation"); left->AddView("org.mitk.views.streamlinetracking"); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp index efbf89450f..d8a7b0e6c8 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp @@ -1,1036 +1,1030 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkControlVisualizationPropertiesView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkTbssImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundle.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include #include #include #include #include #include "mitkGlobalInteraction.h" #include "usModuleRegistry.h" #include "mitkPlaneGeometry.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include #include "qwidgetaction.h" #include "qcolordialog.h" #include #include #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) const std::string QmitkControlVisualizationPropertiesView::VIEW_ID = "org.mitk.views.controlvisualizationpropertiesview"; using namespace berry; QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_NodeUsedForOdfVisualization(NULL), m_IconTexOFF(new QIcon(":/QmitkDiffusionImaging/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkDiffusionImaging/texIntONIcon.png")), m_IconGlyOFF_T(new QIcon(":/QmitkDiffusionImaging/glyphsoff_T.png")), m_IconGlyON_T(new QIcon(":/QmitkDiffusionImaging/glyphson_T.png")), m_IconGlyOFF_C(new QIcon(":/QmitkDiffusionImaging/glyphsoff_C.png")), m_IconGlyON_C(new QIcon(":/QmitkDiffusionImaging/glyphson_C.png")), m_IconGlyOFF_S(new QIcon(":/QmitkDiffusionImaging/glyphsoff_S.png")), m_IconGlyON_S(new QIcon(":/QmitkDiffusionImaging/glyphson_S.png")), m_CurrentSelection(0), m_CurrentPickingNode(0), m_GlyIsOn_S(false), m_GlyIsOn_C(false), m_GlyIsOn_T(false), m_FiberBundleObserverTag(0), m_FiberBundleObserveOpacityTag(0), m_Color(NULL) { currentThickSlicesMode = 1; m_MyMenu = NULL; int numThread = itk::MultiThreader::GetGlobalMaximumNumberOfThreads(); if (numThread > 12) numThread = 12; itk::MultiThreader::SetGlobalDefaultNumberOfThreads(numThread); } -QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - QmitkControlVisualizationPropertiesView::~QmitkControlVisualizationPropertiesView() { if(m_SlicesRotationObserverTag1 ) { mitk::SlicesCoordinator::Pointer coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator.IsNotNull() ) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } if( m_SlicesRotationObserverTag2) { mitk::SlicesCoordinator::Pointer coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator.IsNotNull() ) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); } void QmitkControlVisualizationPropertiesView::OnThickSlicesModeSelected( QAction* action ) { currentThickSlicesMode = action->data().toInt(); switch(currentThickSlicesMode) { default: case 1: this->m_Controls->m_TSMenu->setText("MIP"); break; case 2: this->m_Controls->m_TSMenu->setText("SUM"); break; case 3: this->m_Controls->m_TSMenu->setText("WEIGH"); break; } mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::OnTSNumChanged(int num) { if(num==0) { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( false ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( false ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( false ) ); } else { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( (num>0) ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( (num>0) ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); if(n) n->SetProperty( "reslice.thickslices.showarea", mitk::BoolProperty::New( (num>0) ) ); } m_TSLabel->setText(QString::number(num*2+1)); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) renderer->SendUpdateSlice(); renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) renderer->SendUpdateSlice(); renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) renderer->SendUpdateSlice(); renderer->GetRenderingManager()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS); } void QmitkControlVisualizationPropertiesView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkControlVisualizationPropertiesViewControls; m_Controls->setupUi(parent); this->CreateConnections(); // hide warning (ODFs in rotated planes) m_Controls->m_lblRotatedPlanesWarning->hide(); m_MyMenu = new QMenu(parent); m_Controls->m_TSMenu->setMenu( m_MyMenu ); QIcon iconFiberFade(":/QmitkDiffusionImaging/MapperEfx2D.png"); m_Controls->m_FiberFading2D->setIcon(iconFiberFade); #ifndef DIFFUSION_IMAGING_EXTENDED int size = m_Controls->m_AdditionalScaling->count(); for(int t=0; tm_AdditionalScaling->itemText(t).toStdString() == "Scale by ASR") { m_Controls->m_AdditionalScaling->removeItem(t); } } #endif m_Controls->m_ScalingFrame->setVisible(false); m_Controls->m_NormalizationFrame->setVisible(false); } } void QmitkControlVisualizationPropertiesView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; if (m_MultiWidget) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag1 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } coordinator = m_MultiWidget->GetSlicesSwiveller(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag2 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } } } void QmitkControlVisualizationPropertiesView::SliceRotation(const itk::EventObject&) { // test if plane rotated if( m_GlyIsOn_T || m_GlyIsOn_C || m_GlyIsOn_S ) { if( this->IsPlaneRotated() ) { // show label m_Controls->m_lblRotatedPlanesWarning->show(); } else { //hide label m_Controls->m_lblRotatedPlanesWarning->hide(); } } } void QmitkControlVisualizationPropertiesView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } -void QmitkControlVisualizationPropertiesView::NodeRemoved(const mitk::DataNode* node) +void QmitkControlVisualizationPropertiesView::NodeRemoved(const mitk::DataNode* /*node*/) { } #include void QmitkControlVisualizationPropertiesView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_VisibleOdfsON_T), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_T()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_S), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_S()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_C), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_C()) ); connect( (QObject*)(m_Controls->m_ShowMaxNumber), SIGNAL(editingFinished()), this, SLOT(ShowMaxNumberChanged()) ); connect( (QObject*)(m_Controls->m_NormalizationDropdown), SIGNAL(currentIndexChanged(int)), this, SLOT(NormalizationDropdownChanged(int)) ); connect( (QObject*)(m_Controls->m_ScalingFactor), SIGNAL(valueChanged(double)), this, SLOT(ScalingFactorChanged(double)) ); connect( (QObject*)(m_Controls->m_AdditionalScaling), SIGNAL(currentIndexChanged(int)), this, SLOT(AdditionalScaling(int)) ); connect( (QObject*)(m_Controls->m_ScalingCheckbox), SIGNAL(clicked()), this, SLOT(ScalingCheckbox()) ); connect((QObject*) m_Controls->m_ResetColoring, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationResetColoring())); connect((QObject*) m_Controls->m_FiberFading2D, SIGNAL(clicked()), (QObject*) this, SLOT( Fiber2DfadingEFX() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(sliderReleased()), (QObject*) this, SLOT( FiberSlicingThickness2D() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(valueChanged(int)), (QObject*) this, SLOT( FiberSlicingUpdateLabel(int) )); connect((QObject*) m_Controls->m_Crosshair, SIGNAL(clicked()), (QObject*) this, SLOT(SetInteractor())); connect((QObject*) m_Controls->m_LineWidth, SIGNAL(editingFinished()), (QObject*) this, SLOT(LineWidthChanged())); connect((QObject*) m_Controls->m_TubeWidth, SIGNAL(editingFinished()), (QObject*) this, SLOT(TubeRadiusChanged())); } } void QmitkControlVisualizationPropertiesView::Activated() { } void QmitkControlVisualizationPropertiesView::Deactivated() { } // set diffusion image channel to b0 volume void QmitkControlVisualizationPropertiesView::NodeAdded(const mitk::DataNode *node) { mitk::DataNode* notConst = const_cast(node); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if (isDiffusionImage) { mitk::Image::Pointer dimg = dynamic_cast(notConst->GetData()); // if there is no b0 image in the dataset, the GetB0Indices() returns a vector of size 0 // and hence we cannot set the Property directly to .front() int displayChannelPropertyValue = 0; mitk::BValueMapProperty* bmapproperty = static_cast(dimg->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() ); mitk::DiffusionPropertyHelper::BValueMapType map = bmapproperty->GetBValueMap(); if( map[0].size() > 0) displayChannelPropertyValue = map[0].front(); notConst->SetIntProperty("DisplayChannel", displayChannelPropertyValue ); } } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkControlVisualizationPropertiesView::OnSelectionChanged( std::vector nodes ) { m_Controls->m_BundleControlsFrame->setVisible(false); m_Controls->m_ImageControlsFrame->setVisible(false); if (nodes.size()>1) // only do stuff if one node is selected return; m_Controls->m_NumberGlyphsFrame->setVisible(false); m_Controls->m_GlyphFrame->setVisible(false); m_Controls->m_TSMenu->setVisible(false); m_SelectedNode = NULL; int numOdfImages = 0; for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if(node.IsNull()) continue; mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; m_SelectedNode = node; if (dynamic_cast(nodeData)) { // handle fiber bundle property observers if (m_Color.IsNotNull()) m_Color->RemoveObserver(m_FiberBundleObserverTag); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor ); m_Color = dynamic_cast(node->GetProperty("color", NULL)); if (m_Color.IsNotNull()) m_FiberBundleObserverTag = m_Color->AddObserver( itk::ModifiedEvent(), command ); if (m_Opacity.IsNotNull()) m_Opacity->RemoveObserver(m_FiberBundleObserveOpacityTag); itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetFiberBundleOpacity ); m_Opacity = dynamic_cast(node->GetProperty("opacity", NULL)); if (m_Opacity.IsNotNull()) m_FiberBundleObserveOpacityTag = m_Opacity->AddObserver( itk::ModifiedEvent(), command2 ); m_Controls->m_BundleControlsFrame->setVisible(true); // ??? if(m_CurrentPickingNode != 0 && node.GetPointer() != m_CurrentPickingNode) m_Controls->m_Crosshair->setEnabled(false); else m_Controls->m_Crosshair->setEnabled(true); int width; node->GetIntProperty("shape.linewidth", width); m_Controls->m_LineWidth->setValue(width); float radius; node->GetFloatProperty("shape.tuberadius", radius); m_Controls->m_TubeWidth->setValue(radius); float range; node->GetFloatProperty("Fiber2DSliceThickness",range); mitk::FiberBundle::Pointer fib = dynamic_cast(node->GetData()); mitk::BaseGeometry::Pointer geo = fib->GetGeometry(); mitk::ScalarType max = geo->GetExtentInMM(0); max = std::max(max, geo->GetExtentInMM(1)); max = std::max(max, geo->GetExtentInMM(2)); m_Controls->m_FiberThicknessSlider->setMaximum(max * 10); m_Controls->m_FiberThicknessSlider->setValue(range * 10); m_Controls->m_FiberThicknessSlider->setFocus(); } else if(dynamic_cast(nodeData) || dynamic_cast(nodeData)) { m_Controls->m_ImageControlsFrame->setVisible(true); m_Controls->m_NumberGlyphsFrame->setVisible(true); m_Controls->m_GlyphFrame->setVisible(true); if(m_NodeUsedForOdfVisualization.IsNotNull()) { m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", false); } m_NodeUsedForOdfVisualization = node; m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); int val; node->GetIntProperty("ShowMaxNumber", val); m_Controls->m_ShowMaxNumber->setValue(val); m_Controls->m_NormalizationDropdown->setCurrentIndex(dynamic_cast(node->GetProperty("Normalization"))->GetValueAsId()); float fval; node->GetFloatProperty("Scaling",fval); m_Controls->m_ScalingFactor->setValue(fval); m_Controls->m_AdditionalScaling->setCurrentIndex(dynamic_cast(node->GetProperty("ScaleBy"))->GetValueAsId()); numOdfImages++; } else if(dynamic_cast(nodeData)) { PlanarFigureFocus(); } else if( dynamic_cast(nodeData) ) { m_Controls->m_ImageControlsFrame->setVisible(true); m_Controls->m_TSMenu->setVisible(true); } } if( nodes.empty() ) return; mitk::DataNode::Pointer node = nodes.at(0); if( node.IsNull() ) return; QMenu *myMenu = m_MyMenu; myMenu->clear(); QActionGroup* thickSlicesActionGroup = new QActionGroup(myMenu); thickSlicesActionGroup->setExclusive(true); int currentTSMode = 0; { mitk::ResliceMethodProperty::Pointer m = dynamic_cast(node->GetProperty( "reslice.thickslices" )); if( m.IsNotNull() ) currentTSMode = m->GetValueAsId(); } int maxTS = 30; for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::Image* image = dynamic_cast((*it)->GetData()); if (image) { int size = std::max(image->GetDimension(0), std::max(image->GetDimension(1), image->GetDimension(2))); if (size>maxTS) maxTS=size; } } maxTS /= 2; int currentNum = 0; { mitk::IntProperty::Pointer m = dynamic_cast(node->GetProperty( "reslice.thickslices.num" )); if( m.IsNotNull() ) { currentNum = m->GetValue(); if(currentNum < 0) currentNum = 0; if(currentNum > maxTS) currentNum = maxTS; } } if(currentTSMode==0) currentNum=0; QSlider *m_TSSlider = new QSlider(myMenu); m_TSSlider->setMinimum(0); m_TSSlider->setMaximum(maxTS-1); m_TSSlider->setValue(currentNum); m_TSSlider->setOrientation(Qt::Horizontal); connect( m_TSSlider, SIGNAL( valueChanged(int) ), this, SLOT( OnTSNumChanged(int) ) ); QHBoxLayout* _TSLayout = new QHBoxLayout; _TSLayout->setContentsMargins(4,4,4,4); _TSLayout->addWidget(m_TSSlider); _TSLayout->addWidget(m_TSLabel=new QLabel(QString::number(currentNum*2+1),myMenu)); QWidget* _TSWidget = new QWidget; _TSWidget->setLayout(_TSLayout); QActionGroup* thickSliceModeActionGroup = new QActionGroup(myMenu); thickSliceModeActionGroup->setExclusive(true); QWidgetAction *m_TSSliderAction = new QWidgetAction(myMenu); m_TSSliderAction->setDefaultWidget(_TSWidget); myMenu->addAction(m_TSSliderAction); QAction* mipThickSlicesAction = new QAction(myMenu); mipThickSlicesAction->setActionGroup(thickSliceModeActionGroup); mipThickSlicesAction->setText("MIP (max. intensity proj.)"); mipThickSlicesAction->setCheckable(true); mipThickSlicesAction->setChecked(currentThickSlicesMode==1); mipThickSlicesAction->setData(1); myMenu->addAction( mipThickSlicesAction ); QAction* sumThickSlicesAction = new QAction(myMenu); sumThickSlicesAction->setActionGroup(thickSliceModeActionGroup); sumThickSlicesAction->setText("SUM (sum intensity proj.)"); sumThickSlicesAction->setCheckable(true); sumThickSlicesAction->setChecked(currentThickSlicesMode==2); sumThickSlicesAction->setData(2); myMenu->addAction( sumThickSlicesAction ); QAction* weightedThickSlicesAction = new QAction(myMenu); weightedThickSlicesAction->setActionGroup(thickSliceModeActionGroup); weightedThickSlicesAction->setText("WEIGHTED (gaussian proj.)"); weightedThickSlicesAction->setCheckable(true); weightedThickSlicesAction->setChecked(currentThickSlicesMode==3); weightedThickSlicesAction->setData(3); myMenu->addAction( weightedThickSlicesAction ); connect( thickSliceModeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(OnThickSlicesModeSelected(QAction*)) ); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_S() { m_GlyIsOn_S = m_Controls->m_VisibleOdfsON_S->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_T() { m_GlyIsOn_T = m_Controls->m_VisibleOdfsON_T->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_C() { m_GlyIsOn_C = m_Controls->m_VisibleOdfsON_C->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool QmitkControlVisualizationPropertiesView::IsPlaneRotated() { mitk::Image* currentImage = dynamic_cast( m_NodeUsedForOdfVisualization->GetData() ); if( currentImage == NULL ) { MITK_ERROR << " Casting problems. Returning false"; return false; } mitk::Vector3D imageNormal0 = currentImage->GetSlicedGeometry()->GetAxisVector(0); mitk::Vector3D imageNormal1 = currentImage->GetSlicedGeometry()->GetAxisVector(1); mitk::Vector3D imageNormal2 = currentImage->GetSlicedGeometry()->GetAxisVector(2); imageNormal0.Normalize(); imageNormal1.Normalize(); imageNormal2.Normalize(); double eps = 0.000001; // for all 2D renderwindows of m_MultiWidget check alignment { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( m_MultiWidget->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) test++; if (test==3) return true; } { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( m_MultiWidget->GetRenderWindow2()->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) test++; if (test==3) return true; } { mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( m_MultiWidget->GetRenderWindow3()->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; mitk::Vector3D normal = displayPlane->GetNormal(); normal.Normalize(); int test = 0; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal0.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal1.GetVnlVector()))-1) > eps ) test++; if( fabs(fabs(dot_product(normal.GetVnlVector(),imageNormal2.GetVnlVector()))-1) > eps ) test++; if (test==3) return true; } return false; } void QmitkControlVisualizationPropertiesView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } if (dynamic_cast(m_SelectedNode->GetData()) || dynamic_cast(m_SelectedNode->GetData())) m_SelectedNode->SetIntProperty("ShowMaxNumber", maxNr); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } if (dynamic_cast(m_SelectedNode->GetData()) || dynamic_cast(m_SelectedNode->GetData())) m_SelectedNode->SetProperty("Normalization", normMeth.GetPointer()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ScalingFactorChanged(double scalingFactor) { if (dynamic_cast(m_SelectedNode->GetData()) || dynamic_cast(m_SelectedNode->GetData())) m_SelectedNode->SetFloatProperty("Scaling", scalingFactor); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; #ifdef DIFFUSION_IMAGING_EXTENDED case 2: scaleBy->SetScaleByPrincipalCurvature(); // commented in for SPIE paper, Principle curvature scaling //m_Controls->params_frame->setVisible(true); break; #endif default: scaleBy->SetScaleByNothing(); } if (dynamic_cast(m_SelectedNode->GetData()) || dynamic_cast(m_SelectedNode->GetData())) m_SelectedNode->SetProperty("Normalization", scaleBy.GetPointer()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ScalingCheckbox() { m_Controls->m_ScalingFrame->setVisible( m_Controls->m_ScalingCheckbox->isChecked()); if(!m_Controls->m_ScalingCheckbox->isChecked()) { m_Controls->m_AdditionalScaling->setCurrentIndex(0); m_Controls->m_ScalingFactor->setValue(1.0); } } void QmitkControlVisualizationPropertiesView::Fiber2DfadingEFX() { if (m_SelectedNode && dynamic_cast(m_SelectedNode->GetData()) ) { bool currentMode; m_SelectedNode->GetBoolProperty("Fiber2DfadeEFX", currentMode); m_SelectedNode->SetProperty("Fiber2DfadeEFX", mitk::BoolProperty::New(!currentMode)); dynamic_cast(m_SelectedNode->GetData())->RequestUpdate2D(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingThickness2D() { if (m_SelectedNode && dynamic_cast(m_SelectedNode->GetData())) { float fibThickness = m_Controls->m_FiberThicknessSlider->value() * 0.1; float currentThickness = 0; m_SelectedNode->GetFloatProperty("Fiber2DSliceThickness", currentThickness); if (fabs(fibThickness-currentThickness)<0.001) return; m_SelectedNode->SetProperty("Fiber2DSliceThickness", mitk::FloatProperty::New(fibThickness)); dynamic_cast(m_SelectedNode->GetData())->RequestUpdate2D(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingUpdateLabel(int value) { QString label = "Range %1 mm"; label = label.arg(value * 0.1); m_Controls->label_range->setText(label); FiberSlicingThickness2D(); } void QmitkControlVisualizationPropertiesView::SetFiberBundleOpacity(const itk::EventObject& /*e*/) { if(m_SelectedNode) { mitk::FiberBundle::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor(const itk::EventObject& /*e*/) { if(m_SelectedNode && dynamic_cast(m_SelectedNode->GetData())) { float color[3]; m_SelectedNode->GetColor(color); mitk::FiberBundle::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetFiberColors(color[0]*255, color[1]*255, color[2]*255); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationResetColoring() { if(m_SelectedNode && dynamic_cast(m_SelectedNode->GetData())) { mitk::FiberBundle::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->DoColorCodingOrientationBased(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::PlanarFigureFocus() { if(m_SelectedNode) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (m_SelectedNode->GetData()); if (_PlanarFigure && _PlanarFigure->GetPlaneGeometry()) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); if (m_SelectedNode->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } const mitk::PlaneGeometry* _PlaneGeometry = _PlanarFigure->GetPlaneGeometry(); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry1 = RenderWindow1->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry2 = RenderWindow2->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry3 = RenderWindow3->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = RenderWindow1; } else { if(ang2 < ang3) { selectedRenderWindow = RenderWindow2; } else { selectedRenderWindow = RenderWindow3; } } // make node visible if (selectedRenderWindow) { const mitk::Point3D& centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(m_SelectedNode->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "MitkPlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( m_SelectedNode ); } m_SelectedNode->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } void QmitkControlVisualizationPropertiesView::SetInteractor() { typedef std::vector Container; Container _NodeSet = this->GetDataManagerSelection(); mitk::DataNode* node = 0; mitk::FiberBundle* bundle = 0; mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // finally add all nodes to the model for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() ; it++) { node = const_cast(*it); bundle = dynamic_cast(node->GetData()); if(bundle) { bundleInteractor = dynamic_cast(node->GetInteractor()); if(bundleInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); if(!m_Controls->m_Crosshair->isChecked()) { m_Controls->m_Crosshair->setChecked(false); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); m_CurrentPickingNode = 0; } else { m_Controls->m_Crosshair->setChecked(true); bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); m_CurrentPickingNode = node; } } } } void QmitkControlVisualizationPropertiesView::TubeRadiusChanged() { if(m_SelectedNode && dynamic_cast(m_SelectedNode->GetData())) { float newRadius = m_Controls->m_TubeWidth->value(); m_SelectedNode->SetFloatProperty("shape.tuberadius", newRadius); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::LineWidthChanged() { if(m_SelectedNode && dynamic_cast(m_SelectedNode->GetData())) { int newWidth = m_Controls->m_LineWidth->value(); int currentWidth = 0; m_SelectedNode->GetIntProperty("shape.linewidth", currentWidth); if (currentWidth==newWidth) return; m_SelectedNode->SetIntProperty("shape.linewidth", newWidth); dynamic_cast(m_SelectedNode->GetData())->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkControlVisualizationPropertiesView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( GetSite()->GetWorkbenchWindow(), false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h index 1b890d9d1c..7bd8ede02b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.h @@ -1,154 +1,153 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKControlVisualizationPropertiesView_H_INCLUDED #define _QMITKControlVisualizationPropertiesView_H_INCLUDED #include #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include "berryISizeProvider.h" #include "ui_QmitkControlVisualizationPropertiesViewControls.h" #include "mitkEnumerationProperty.h" /*! * \ingroup org_mitk_gui_qt_diffusionquantification_internal * * \brief QmitkControlVisualizationPropertiesView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkControlVisualizationPropertiesView : public QmitkFunctionality//, public berry::ISizeProvider { friend struct CvpSelListener; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkControlVisualizationPropertiesView(); - QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other); virtual ~QmitkControlVisualizationPropertiesView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: void VisibleOdfsON_S(); void VisibleOdfsON_T(); void VisibleOdfsON_C(); void ShowMaxNumberChanged(); void NormalizationDropdownChanged(int); void ScalingFactorChanged(double); void AdditionalScaling(int); void ScalingCheckbox(); void OnThickSlicesModeSelected( QAction* action ); void OnTSNumChanged(int num); void BundleRepresentationResetColoring(); void PlanarFigureFocus(); void Fiber2DfadingEFX(); void FiberSlicingThickness2D(); void FiberSlicingUpdateLabel(int); void LineWidthChanged(); void TubeRadiusChanged(); void SetInteractor(); void Welcome(); protected: virtual void NodeRemoved(const mitk::DataNode* node); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); virtual void NodeAdded(const mitk::DataNode *node); void SetFiberBundleCustomColor(const itk::EventObject& /*e*/); void SetFiberBundleOpacity(const itk::EventObject& /*e*/); bool IsPlaneRotated(); void SliceRotation(const itk::EventObject&); Ui::QmitkControlVisualizationPropertiesViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; - berry::ISelectionListener::Pointer m_SelListener; + QScopedPointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; mitk::DataNode::Pointer m_NodeUsedForOdfVisualization; QIcon* m_IconTexOFF; QIcon* m_IconTexON; QIcon* m_IconGlyOFF_T; QIcon* m_IconGlyON_T; QIcon* m_IconGlyOFF_C; QIcon* m_IconGlyON_C; QIcon* m_IconGlyOFF_S; QIcon* m_IconGlyON_S; bool m_TexIsOn; bool m_GlyIsOn_T; bool m_GlyIsOn_C; bool m_GlyIsOn_S; int currentThickSlicesMode; QLabel* m_TSLabel; QMenu* m_MyMenu; // for planarfigure and bundle handling: mitk::DataNode::Pointer m_SelectedNode; mitk::DataNode* m_CurrentPickingNode; unsigned long m_SlicesRotationObserverTag1; unsigned long m_SlicesRotationObserverTag2; unsigned long m_FiberBundleObserverTag; unsigned long m_FiberBundleObserveOpacityTag; mitk::ColorProperty::Pointer m_Color; mitk::FloatProperty::Pointer m_Opacity; }; #endif // _QMITKControlVisualizationPropertiesView_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp index c116f927ea..e04072db6c 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.cpp @@ -1,1120 +1,1119 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkQBallReconstructionView.h" // qt includes #include // itk includes #include "itkTimeProbe.h" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "itkDiffusionQballReconstructionImageFilter.h" #include "itkAnalyticalDiffusionQballReconstructionImageFilter.h" #include "itkDiffusionMultiShellQballReconstructionImageFilter.h" #include "itkVectorContainer.h" #include "itkB0ImageExtractionImageFilter.h" #include #include "mitkQBallImage.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include #include "mitkDiffusionImagingConfigure.h" #include "berryIStructuredSelection.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" #include const std::string QmitkQBallReconstructionView::VIEW_ID = "org.mitk.views.qballreconstruction"; typedef float TTensorPixelType; const int QmitkQBallReconstructionView::nrconvkernels = 252; struct QbrShellSelection { typedef mitk::DiffusionPropertyHelper::GradientDirectionType GradientDirectionType; typedef mitk::DiffusionPropertyHelper::GradientDirectionsContainerType GradientDirectionContainerType; typedef mitk::DiffusionPropertyHelper::BValueMapType BValueMapType; typedef itk::VectorImage< DiffusionPixelType, 3 > ITKDiffusionImageType; QmitkQBallReconstructionView* m_View; mitk::DataNode * m_Node; std::string m_NodeName; std::vector m_CheckBoxes; QLabel * m_Label; mitk::Image * m_Image; QbrShellSelection(QmitkQBallReconstructionView* view, mitk::DataNode * node) : m_View(view), m_Node(node), m_NodeName(node->GetName()) { m_Image = dynamic_cast (node->GetData()); if(!m_Image) { MITK_ERROR << "QmitkQBallReconstructionView::QbrShellSelection : no image selected"; return; } bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(m_Node->GetData())) ); if( !isDiffusionImage ) { MITK_ERROR << "QmitkQBallReconstructionView::QbrShellSelection : selected image contains no diffusion information"; return; } GenerateCheckboxes(); } void GenerateCheckboxes() { BValueMapType origMap = static_cast(m_Image->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() )->GetBValueMap(); BValueMapType::iterator itStart = origMap.begin(); itStart++; BValueMapType::iterator itEnd = origMap.end(); m_Label = new QLabel(m_NodeName.c_str()); m_Label->setVisible(true); m_View->m_Controls->m_QBallSelectionBox->layout()->addWidget(m_Label); for(BValueMapType::iterator it = itStart ; it!= itEnd; it++) { QCheckBox * box = new QCheckBox(QString::number(it->first)); m_View->m_Controls->m_QBallSelectionBox->layout()->addWidget(box); box->setChecked(true); box->setCheckable(true); // box->setVisible(true); m_CheckBoxes.push_back(box); } } void SetVisible(bool vis) { foreach(QCheckBox * box, m_CheckBoxes) { box->setVisible(vis); } } BValueMapType GetBValueSelctionMap() { BValueMapType inputMap = static_cast(m_Image->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() )->GetBValueMap(); BValueMapType outputMap; unsigned int val = 0; if(inputMap.find(0) == inputMap.end()){ MITK_INFO << "QbrShellSelection: return empty BValueMap from GUI Selection"; return outputMap; }else{ outputMap[val] = inputMap[val]; MITK_INFO << val; } foreach(QCheckBox * box, m_CheckBoxes) { if(box->isChecked()){ val = box->text().toDouble(); outputMap[val] = inputMap[val]; MITK_INFO << val; } } return outputMap; } ~QbrShellSelection() { m_View->m_Controls->m_QBallSelectionBox->layout()->removeWidget(m_Label); delete m_Label; for(std::vector::iterator it = m_CheckBoxes.begin() ; it!= m_CheckBoxes.end(); it++) { m_View->m_Controls->m_QBallSelectionBox->layout()->removeWidget((*it)); delete (*it); } m_CheckBoxes.clear(); } }; using namespace berry; struct QbrSelListener : ISelectionListener { - berryObjectMacro(QbrSelListener); - QbrSelListener(QmitkQBallReconstructionView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { bool foundDwiVolume = false; m_View->m_Controls->m_DiffusionImageLabel->setText("mandatory"); m_View->m_Controls->m_InputData->setTitle("Please Select Input Data"); QString selected_images = ""; mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); mitk::Image* diffusionImage = dynamic_cast(node->GetData()); // only look at interesting types if(diffusionImage && isDiffusionImage) { foundDwiVolume = true; selected_images += QString(node->GetName().c_str()); if(i + 1 != m_View->m_CurrentSelection->End()) selected_images += "\n"; set->InsertElement(at++, node); } } } m_View->GenerateShellSelectionUI(set); m_View->m_Controls->m_DiffusionImageLabel->setText(selected_images); m_View->m_Controls->m_ButtonStandard->setEnabled(foundDwiVolume); if (foundDwiVolume) m_View->m_Controls->m_InputData->setTitle("Input Data"); else m_View->m_Controls->m_DiffusionImageLabel->setText("mandatory"); } } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& selection) override { // check, if selection comes from datamanager if (part) { - QString partname(part->GetPartName().c_str()); - if(partname.compare("Data Manager")==0) + QString partname = part->GetPartName(); + if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkQBallReconstructionView* m_View; }; // --------------- QmitkQBallReconstructionView----------------- // QmitkQBallReconstructionView::QmitkQBallReconstructionView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { } QmitkQBallReconstructionView::~QmitkQBallReconstructionView() { - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); } void QmitkQBallReconstructionView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkQBallReconstructionViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_DiffusionImageLabel->setText("mandatory"); QStringList items; items << "2" << "4" << "6" << "8" << "10" << "12"; m_Controls->m_QBallReconstructionMaxLLevelComboBox->addItems(items); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setCurrentIndex(1); MethodChoosen(m_Controls->m_QBallReconstructionMethodComboBox->currentIndex()); #ifndef DIFFUSION_IMAGING_EXTENDED m_Controls->m_QBallReconstructionMethodComboBox->removeItem(3); #endif AdvancedCheckboxClicked(); } - m_SelListener = berry::ISelectionListener::Pointer(new QbrSelListener(this)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + m_SelListener.reset(new QbrSelListener(this)); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); + static_cast(m_SelListener.data())->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkQBallReconstructionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkQBallReconstructionView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonStandard), SIGNAL(clicked()), this, SLOT(ReconstructStandard()) ); connect( (QObject*)(m_Controls->m_AdvancedCheckbox), SIGNAL(clicked()), this, SLOT(AdvancedCheckboxClicked()) ); connect( (QObject*)(m_Controls->m_QBallReconstructionMethodComboBox), SIGNAL(currentIndexChanged(int)), this, SLOT(MethodChoosen(int)) ); connect( (QObject*)(m_Controls->m_QBallReconstructionThreasholdEdit), SIGNAL(valueChanged(int)), this, SLOT(PreviewThreshold(int)) ); } } void QmitkQBallReconstructionView::OnSelectionChanged( std::vector ) { } void QmitkQBallReconstructionView::Activated() { QmitkFunctionality::Activated(); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); + static_cast(m_SelListener.data())->DoSelectionChanged(sel); } void QmitkQBallReconstructionView::Deactivated() { mitk::DataStorage::SetOfObjects::ConstPointer objects = this->GetDefaultDataStorage()->GetAll(); mitk::DataStorage::SetOfObjects::const_iterator itemiter( objects->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( objects->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DataNode::Pointer node = *itemiter; if (node.IsNull()) continue; // only look at interesting types bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if( isDiffusionImage ) { if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); this->GetDefaultDataStorage()->Remove(node); } } itemiter++; } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated(); } void QmitkQBallReconstructionView::ReconstructStandard() { int index = m_Controls->m_QBallReconstructionMethodComboBox->currentIndex(); #ifndef DIFFUSION_IMAGING_EXTENDED if(index>=3) { index = index + 1; } #endif switch(index) { case 0: { // Numerical Reconstruct(0,0); break; } case 1: { // Standard Reconstruct(1,0); break; } case 2: { // Solid Angle Reconstruct(1,6); break; } case 3: { // Constrained Solid Angle Reconstruct(1,7); break; } case 4: { // ADC Reconstruct(1,4); break; } case 5: { // Raw Signal Reconstruct(1,5); break; } case 6: { // Q-Ball reconstruction Reconstruct(2,0); break; } } } void QmitkQBallReconstructionView::MethodChoosen(int method) { #ifndef DIFFUSION_IMAGING_EXTENDED if(method>=3) { method = method + 1; } #endif m_Controls->m_QBallSelectionBox->setHidden(true); m_Controls->m_OutputCoeffsImage->setHidden(true); if (method==0) m_Controls->m_ShFrame->setVisible(false); else m_Controls->m_ShFrame->setVisible(true); switch(method) { case 0: m_Controls->m_Description->setText("Numerical recon. (Tuch 2004)"); break; case 1: m_Controls->m_Description->setText("Spherical harmonics recon. (Descoteaux 2007)"); m_Controls->m_OutputCoeffsImage->setHidden(false); break; case 2: m_Controls->m_Description->setText("SH recon. with solid angle consideration (Aganj 2009)"); m_Controls->m_OutputCoeffsImage->setHidden(false); break; case 3: m_Controls->m_Description->setText("SH solid angle with non-neg. constraint (Goh 2009)"); break; case 4: m_Controls->m_Description->setText("SH recon. of the plain ADC-profiles"); break; case 5: m_Controls->m_Description->setText("SH recon. of the raw diffusion signal"); break; case 6: m_Controls->m_Description->setText("SH recon. of the multi shell diffusion signal (Aganj 2010)"); m_Controls->m_QBallSelectionBox->setHidden(false); m_Controls->m_OutputCoeffsImage->setHidden(false); break; } } void QmitkQBallReconstructionView::AdvancedCheckboxClicked() { bool check = m_Controls->m_AdvancedCheckbox->isChecked(); m_Controls->m_QBallReconstructionMaxLLevelTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionMaxLLevelComboBox->setVisible(check); m_Controls->m_QBallReconstructionLambdaTextLabel_2->setVisible(check); m_Controls->m_QBallReconstructionLambdaLineEdit->setVisible(check); m_Controls->m_QBallReconstructionThresholdLabel_2->setVisible(check); m_Controls->m_QBallReconstructionThreasholdEdit->setVisible(check); m_Controls->label_2->setVisible(check); m_Controls->frame_2->setVisible(check); } void QmitkQBallReconstructionView::Reconstruct(int method, int normalization) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if ( isDiffusionImage ) { set->InsertElement(at++, node); } } } if(method == 0) { NumericalQBallReconstruction(set, normalization); } else { #if BOOST_VERSION / 100000 > 0 #if BOOST_VERSION / 100 % 1000 > 34 if(method == 1) { AnalyticalQBallReconstruction(set, normalization); } if(method == 2) { MultiQBallReconstruction(set); } #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif #else std::cout << "ERROR: Boost 1.35 minimum required" << std::endl; QMessageBox::warning(NULL,"ERROR","Boost 1.35 minimum required"); #endif } } } void QmitkQBallReconstructionView::NumericalQBallReconstruction (mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "QBall reconstruction for %s", nodename.c_str()).toLatin1()); typedef itk::DiffusionQballReconstructionImageFilter QballReconstructionImageFilterType; ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetGradientImage( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer ); filter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); std::string nodePostfix; switch(normalization) { case 0: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); nodePostfix = "_Numerical_Qball"; break; } case 1: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO_B_VALUE); nodePostfix = "_Numerical_ZeroBvalueNormalization_Qball"; break; } case 2: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_B_ZERO); nodePostfix = "_NumericalQball_ZeroNormalization_Qball"; break; } case 3: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_NONE); nodePostfix = "_NumericalQball_NoNormalization_Qball"; break; } default: { filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); nodePostfix = "_NumericalQball_Qball"; } } filter->Update(); clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+nodePostfix); mitk::ProgressBar::GetInstance()->Progress(); GetDefaultDataStorage()->Add(node, *itemiter); ++itemiter; } mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return ; } } void QmitkQBallReconstructionView::AnalyticalQBallReconstruction( mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->value(); lambdas.push_back(minLambda); int nLambdas = lambdas.size(); QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles*nLambdas); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); std::vector* nodes = new std::vector(); while ( itemiter != itemiterend ) // for all items { // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("QBall reconstruction for %s", (*itemiter)->GetName().c_str()).toLatin1()); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentIndex()) { case 0: { TemplatedAnalyticalQBallReconstruction<2>(*itemiter, currentLambda, normalization); break; } case 1: { TemplatedAnalyticalQBallReconstruction<4>(*itemiter, currentLambda, normalization); break; } case 2: { TemplatedAnalyticalQBallReconstruction<6>(*itemiter, currentLambda, normalization); break; } case 3: { TemplatedAnalyticalQBallReconstruction<8>(*itemiter, currentLambda, normalization); break; } case 4: { TemplatedAnalyticalQBallReconstruction<10>(*itemiter, currentLambda, normalization); break; } case 5: { TemplatedAnalyticalQBallReconstruction<12>(*itemiter, currentLambda, normalization); break; } } clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; mitk::ProgressBar::GetInstance()->Progress(); itemiter++; } } std::vector::iterator nodeIt; for(nodeIt = nodes->begin(); nodeIt != nodes->end(); ++nodeIt) GetDefaultDataStorage()->Add(*nodeIt); m_MultiWidget->RequestUpdate(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return; } } template void QmitkQBallReconstructionView::TemplatedAnalyticalQBallReconstruction(mitk::DataNode* dataNodePointer, float lambda, int normalization) { typedef itk::AnalyticalDiffusionQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); mitk::Image* vols = dynamic_cast(dataNodePointer->GetData()); ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); filter->SetGradientImage( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer ); filter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); filter->SetLambda(lambda); std::string nodePostfix; switch(normalization) { case 0: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); nodePostfix = "_SphericalHarmonics_Qball"; break; } case 1: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO_B_VALUE); nodePostfix = "_SphericalHarmonics_1_Qball"; break; } case 2: { filter->SetNormalizationMethod(FilterType::QBAR_B_ZERO); nodePostfix = "_SphericalHarmonics_2_Qball"; break; } case 3: { filter->SetNormalizationMethod(FilterType::QBAR_NONE); nodePostfix = "_SphericalHarmonics_3_Qball"; break; } case 4: { filter->SetNormalizationMethod(FilterType::QBAR_ADC_ONLY); nodePostfix = "_AdcProfile"; break; } case 5: { filter->SetNormalizationMethod(FilterType::QBAR_RAW_SIGNAL); nodePostfix = "_RawSignal"; break; } case 6: { filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); nodePostfix = "_SphericalHarmonics_CSA_Qball"; break; } case 7: { filter->SetNormalizationMethod(FilterType::QBAR_NONNEG_SOLID_ANGLE); nodePostfix = "_SphericalHarmonics_NonNegCSA_Qball"; break; } default: { filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); } } filter->Update(); // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, dataNodePointer->GetName()+nodePostfix); GetDefaultDataStorage()->Add(node, dataNodePointer); if(m_Controls->m_OutputCoeffsImage->isChecked()) { mitk::Image::Pointer coeffsImage = mitk::Image::New(); coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); mitk::DataNode::Pointer coeffsNode=mitk::DataNode::New(); coeffsNode->SetData( coeffsImage ); coeffsNode->SetProperty( "name", mitk::StringProperty::New(dataNodePointer->GetName()+"_SH-Coeffs") ); coeffsNode->SetVisibility(false); GetDefaultDataStorage()->Add(coeffsNode, node); } } void QmitkQBallReconstructionView::MultiQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; std::vector lambdas; float minLambda = m_Controls->m_QBallReconstructionLambdaLineEdit->value(); lambdas.push_back(minLambda); int nLambdas = lambdas.size(); QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles*nLambdas); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DataNode* nodePointer = (*itemiter).GetPointer(); std::string nodename; (*itemiter)->GetStringProperty("name",nodename); itemiter++; // QBALL RECONSTRUCTION clock.Start(); MITK_INFO << "QBall reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("QBall reconstruction for %s", nodename.c_str()).toLatin1()); for(int i=0; im_QBallReconstructionMaxLLevelComboBox->currentIndex()) { case 0: { TemplatedMultiQBallReconstruction<2>(currentLambda, nodePointer); break; } case 1: { TemplatedMultiQBallReconstruction<4>(currentLambda, nodePointer); break; } case 2: { TemplatedMultiQBallReconstruction<6>(currentLambda, nodePointer); break; } case 3: { TemplatedMultiQBallReconstruction<8>(currentLambda, nodePointer); break; } case 4: { TemplatedMultiQBallReconstruction<10>(currentLambda, nodePointer); break; } case 5: { TemplatedMultiQBallReconstruction<12>(currentLambda, nodePointer); break; } } clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s." ; mitk::ProgressBar::GetInstance()->Progress(); } } m_MultiWidget->RequestUpdate(); mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return ; } } template void QmitkQBallReconstructionView::TemplatedMultiQBallReconstruction(float lambda, mitk::DataNode* dataNodePointer) { typedef itk::DiffusionMultiShellQballReconstructionImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); std::string nodename; dataNodePointer->GetStringProperty("name",nodename); mitk::Image* dwi = dynamic_cast(dataNodePointer->GetData()); BValueMapType currSelectionMap = m_ShellSelectorMap[dataNodePointer]->GetBValueSelctionMap(); if(currSelectionMap.size() != 4 && currSelectionMap.find(0) != currSelectionMap.end()) { QMessageBox::information(0, "Reconstruction not possible:" ,QString("Only three shells in a equidistant configuration is supported. (ImageName: " + QString(nodename.c_str()) + ")")); return; } BValueMapType::reverse_iterator it1 = currSelectionMap.rbegin(); BValueMapType::reverse_iterator it2 = currSelectionMap.rbegin(); ++it2; // Get average distance int avdistance = 0; for(; it2 != currSelectionMap.rend(); ++it1,++it2) avdistance += (int)it1->first - (int)it2->first; avdistance /= currSelectionMap.size()-1; // Check if all shells are using the same averae distance it1 = currSelectionMap.rbegin(); it2 = currSelectionMap.rbegin(); ++it2; for(; it2 != currSelectionMap.rend(); ++it1,++it2) if(avdistance != (int)it1->first - (int)it2->first) { QMessageBox::information(0, "Reconstruction not possible:" ,QString("Selected Shells are not in a equidistant configuration. (ImageName: " + QString(nodename.c_str()) + ")")); return; } ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(dwi, itkVectorImagePointer); filter->SetBValueMap(m_ShellSelectorMap[dataNodePointer]->GetBValueSelctionMap()); filter->SetGradientImage( static_cast( dwi->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(), itkVectorImagePointer, static_cast(dwi->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); filter->SetThreshold( m_Controls->m_QBallReconstructionThreasholdEdit->value() ); filter->SetLambda(lambda); filter->Update(); // ODFs TO DATATREE mitk::QBallImage::Pointer image = mitk::QBallImage::New(); image->InitializeByItk( filter->GetOutput() ); image->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+"_SphericalHarmonics_MultiShell_Qball"); GetDefaultDataStorage()->Add(node, dataNodePointer); if(m_Controls->m_OutputCoeffsImage->isChecked()) { mitk::Image::Pointer coeffsImage = mitk::Image::New(); coeffsImage->InitializeByItk( filter->GetCoefficientImage().GetPointer() ); coeffsImage->SetVolume( filter->GetCoefficientImage()->GetBufferPointer() ); mitk::DataNode::Pointer coeffsNode=mitk::DataNode::New(); coeffsNode->SetData( coeffsImage ); coeffsNode->SetProperty( "name", mitk::StringProperty::New( QString(nodename.c_str()).append("_SH-Coefficients").toStdString()) ); coeffsNode->SetVisibility(false); GetDefaultDataStorage()->Add(coeffsNode, node); } } void QmitkQBallReconstructionView::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 500 ) ); node->SetProperty( "Scaling", mitk::FloatProperty::New( 1.0 ) ); node->SetProperty( "Normalization", mitk::OdfNormalizationMethodProperty::New()); node->SetProperty( "ScaleBy", mitk::OdfScaleByProperty::New()); node->SetProperty( "IndexParam1", mitk::FloatProperty::New(2)); node->SetProperty( "IndexParam2", mitk::FloatProperty::New(1)); node->SetProperty( "visible", mitk::BoolProperty::New( true ) ); node->SetProperty( "VisibleOdfs", mitk::BoolProperty::New( false ) ); node->SetProperty ("layer", mitk::IntProperty::New(100)); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); node->SetProperty( "name", mitk::StringProperty::New(name) ); } void QmitkQBallReconstructionView::GenerateShellSelectionUI(mitk::DataStorage::SetOfObjects::Pointer set) { m_DiffusionImages = set; std::map tempMap; const mitk::DataStorage::SetOfObjects::iterator setEnd( set->end() ); mitk::DataStorage::SetOfObjects::iterator NodeIt( set->begin() ); while(NodeIt != setEnd) { if(m_ShellSelectorMap.find( (*NodeIt).GetPointer() ) != m_ShellSelectorMap.end()) { tempMap[(*NodeIt).GetPointer()] = m_ShellSelectorMap[(*NodeIt).GetPointer()]; m_ShellSelectorMap.erase((*NodeIt).GetPointer()); }else { tempMap[(*NodeIt).GetPointer()] = new QbrShellSelection(this, (*NodeIt) ); tempMap[(*NodeIt).GetPointer()]->SetVisible(true); } NodeIt++; } for(std::map::iterator it = m_ShellSelectorMap.begin(); it != m_ShellSelectorMap.end();it ++) { delete it->second; } m_ShellSelectorMap.clear(); m_ShellSelectorMap = tempMap; } void QmitkQBallReconstructionView::PreviewThreshold(int threshold) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_DiffusionImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_DiffusionImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); // Extract b0 image ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filterB0 = FilterType::New(); filterB0->SetInput( itkVectorImagePointer ); filterB0->SetDirections( static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer() ); filterB0->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); typedef itk::Image ImageType; typedef itk::Image SegmentationType; typedef itk::BinaryThresholdImageFilter ThresholdFilterType; // apply threshold ThresholdFilterType::Pointer filterThreshold = ThresholdFilterType::New(); filterThreshold->SetInput(filterB0->GetOutput()); filterThreshold->SetLowerThreshold(threshold); filterThreshold->SetInsideValue(0); filterThreshold->SetOutsideValue(1); // mark cut off values red filterThreshold->Update(); mitkImage->InitializeByItk( filterThreshold->GetOutput() ); mitkImage->SetVolume( filterThreshold->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node; if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); } else { // create a new node, to show thresholded values node = mitk::DataNode::New(); GetDefaultDataStorage()->Add( node, *itemiter ); node->SetProperty( "name", mitk::StringProperty::New("ThresholdOverlay")); node->SetBoolProperty("helper object", true); } node->SetData( mitkImage ); itemiter++; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h index d6cc9382ce..8f07dab5e3 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkQBallReconstructionView.h @@ -1,138 +1,138 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED #define _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED #include #include #include "ui_QmitkQBallReconstructionViewControls.h" #include #include #include #include #include #include typedef short DiffusionPixelType; struct QbrSelListener; struct QbrShellSelection; /*! * \ingroup org_mitk_gui_qt_qballreconstruction_internal * * \brief QmitkQBallReconstructionView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkQBallReconstructionView : public QmitkFunctionality { friend struct QbrSelListener; friend struct QbrShellSelection; typedef mitk::DiffusionPropertyHelper::GradientDirectionType GradientDirectionType; typedef mitk::DiffusionPropertyHelper::GradientDirectionsContainerType GradientDirectionContainerType; typedef mitk::DiffusionPropertyHelper::BValueMapType BValueMapType; typedef itk::VectorImage< DiffusionPixelType, 3 > ITKDiffusionImageType; // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkQBallReconstructionView(); virtual ~QmitkQBallReconstructionView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); static const int nrconvkernels; protected slots: void ReconstructStandard(); void AdvancedCheckboxClicked(); void MethodChoosen(int method); void Reconstruct(int method, int normalization); void NumericalQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization); void AnalyticalQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages, int normalization); void MultiQBallReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages); /** * @brief PreviewThreshold Generates a preview of the values that are cut off by the thresholds * @param threshold */ void PreviewThreshold(int threshold); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkQBallReconstructionViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; template void TemplatedAnalyticalQBallReconstruction(mitk::DataNode* dataNodePointer, float lambda, int normalization); template void TemplatedMultiQBallReconstruction(float lambda, mitk::DataNode*); void SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name); //void Create - berry::ISelectionListener::Pointer m_SelListener; + QScopedPointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; mitk::DataStorage::SetOfObjects::Pointer m_DiffusionImages; private: std::map< const mitk::DataNode *, QbrShellSelection * > m_ShellSelectorMap; void GenerateShellSelectionUI(mitk::DataStorage::SetOfObjects::Pointer set); }; #endif // _QMITKQBALLRECONSTRUCTIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp index f71eae8d1c..fc890225ad 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkTensorReconstructionView.cpp @@ -1,1068 +1,1068 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkTensorReconstructionView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include #include #include #include #include // itk includes #include "itkTimeProbe.h" //#include "itkTensor.h" // mitk includes #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkTeemDiffusionTensor3DReconstructionImageFilter.h" #include "itkDiffusionTensor3DReconstructionImageFilter.h" #include "itkTensorImageToDiffusionImageFilter.h" #include "itkPointShell.h" #include "itkVector.h" #include "itkB0ImageExtractionImageFilter.h" #include "itkTensorReconstructionWithEigenvalueCorrectionFilter.h" #include "mitkImageCast.h" #include "mitkImageAccessByItk.h" #include #include #include "mitkProperties.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkLookupTableProperty.h" #include "mitkLookupTable.h" #include "mitkImageStatisticsHolder.h" #include #include #include #include #include #include const std::string QmitkTensorReconstructionView::VIEW_ID = "org.mitk.views.tensorreconstruction"; typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; using namespace berry; QmitkTensorReconstructionView::QmitkTensorReconstructionView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { m_DiffusionImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); } QmitkTensorReconstructionView::~QmitkTensorReconstructionView() { } void QmitkTensorReconstructionView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkTensorReconstructionViewControls; m_Controls->setupUi(parent); this->CreateConnections(); Advanced1CheckboxClicked(); } } void QmitkTensorReconstructionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkTensorReconstructionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkTensorReconstructionView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_StartReconstruction), SIGNAL(clicked()), this, SLOT(Reconstruct()) ); connect( (QObject*)(m_Controls->m_Advanced1), SIGNAL(clicked()), this, SLOT(Advanced1CheckboxClicked()) ); connect( (QObject*)(m_Controls->m_TensorsToDWIButton), SIGNAL(clicked()), this, SLOT(TensorsToDWI()) ); connect( (QObject*)(m_Controls->m_TensorsToQbiButton), SIGNAL(clicked()), this, SLOT(TensorsToQbi()) ); connect( (QObject*)(m_Controls->m_ResidualButton), SIGNAL(clicked()), this, SLOT(ResidualCalculation()) ); connect( (QObject*)(m_Controls->m_PerSliceView), SIGNAL(pointSelected(int, int)), this, SLOT(ResidualClicked(int, int)) ); connect( (QObject*)(m_Controls->m_TensorReconstructionThreshold), SIGNAL(valueChanged(int)), this, SLOT(PreviewThreshold(int)) ); } } void QmitkTensorReconstructionView::ResidualClicked(int slice, int volume) { // Use image coord to reset crosshair // Find currently selected diffusion image // Update Label // to do: This position should be modified in order to skip B0 volumes that are not taken into account // when calculating residuals // Find the diffusion image mitk::Image* diffImage; mitk::DataNode::Pointer correctNode; mitk::BaseGeometry* geometry; bool isDiffusionImage(false); if (m_DiffusionImage.IsNotNull()) { isDiffusionImage = mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(m_DiffusionImage->GetData())) ; diffImage = static_cast(m_DiffusionImage->GetData()); geometry = m_DiffusionImage->GetData()->GetGeometry(); // Remember the node whose display index must be updated correctNode = mitk::DataNode::New(); correctNode = m_DiffusionImage; } if( isDiffusionImage ) { GradientDirectionContainerType::Pointer dirs = static_cast( diffImage->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(); for(unsigned int i=0; iSize() && i<=volume; i++) { GradientDirectionType grad = dirs->ElementAt(i); // check if image is b0 weighted if(fabs(grad[0]) < 0.001 && fabs(grad[1]) < 0.001 && fabs(grad[2]) < 0.001) { volume++; } } QString pos = "Volume: "; pos.append(QString::number(volume)); pos.append(", Slice: "); pos.append(QString::number(slice)); m_Controls->m_PositionLabel->setText(pos); if(correctNode) { int oldDisplayVal; correctNode->GetIntProperty("DisplayChannel", oldDisplayVal); - std::string oldVal = QString::number(oldDisplayVal).toStdString(); - std::string newVal = QString::number(volume).toStdString(); + QString oldVal = QString::number(oldDisplayVal); + QString newVal = QString::number(volume); correctNode->SetIntProperty("DisplayChannel",volume); correctNode->SetSelected(true); this->FirePropertyChanged("DisplayChannel", oldVal, newVal); correctNode->UpdateOutputInformation(); mitk::Point3D p3 = m_MultiWidget->GetCrossPosition(); itk::Index<3> ix; geometry->WorldToIndex(p3, ix); // ix[2] = slice; mitk::Vector3D vec; vec[0] = ix[0]; vec[1] = ix[1]; vec[2] = slice; mitk::Vector3D v3New; geometry->IndexToWorld(vec, v3New); mitk::Point3D origin = geometry->GetOrigin(); mitk::Point3D p3New; p3New[0] = v3New[0] + origin[0]; p3New[1] = v3New[1] + origin[1]; p3New[2] = v3New[2] + origin[2]; m_MultiWidget->MoveCrossToPosition(p3New); m_MultiWidget->RequestUpdate(); } } } void QmitkTensorReconstructionView::Advanced1CheckboxClicked() { bool check = m_Controls-> m_Advanced1->isChecked(); m_Controls->frame->setVisible(check); } void QmitkTensorReconstructionView::Activated() { QmitkFunctionality::Activated(); } void QmitkTensorReconstructionView::Deactivated() { // Get all current nodes mitk::DataStorage::SetOfObjects::ConstPointer objects = this->GetDefaultDataStorage()->GetAll(); mitk::DataStorage::SetOfObjects::const_iterator itemiter( objects->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( objects->end() ); while ( itemiter != itemiterend ) // for all items { mitk::DataNode::Pointer node = *itemiter; if (node.IsNull()) continue; // only look at interesting types if( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(dynamic_cast(node->GetData()))) { if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); this->GetDefaultDataStorage()->Remove(node); } } itemiter++; } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated(); } void QmitkTensorReconstructionView::ResidualCalculation() { // Extract dwi and dti from current selection // In case of multiple selections, take the first one, since taking all combinations is not meaningful mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); mitk::Image::Pointer diffImage = mitk::Image::New(); TensorImageType::Pointer tensorImage; std::string nodename; if(m_DiffusionImage.IsNotNull()) { diffImage = static_cast(m_DiffusionImage->GetData()); } else return; if(m_TensorImage.IsNotNull()) { mitk::TensorImage* mitkVol; mitkVol = static_cast(m_TensorImage->GetData()); mitk::CastToItkImage(mitkVol, tensorImage); m_TensorImage->GetStringProperty("name", nodename); } else return; typedef itk::TensorImageToDiffusionImageFilter< TTensorPixelType, DiffusionPixelType > FilterType; GradientDirectionContainerType* gradients = static_cast( diffImage->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer(); // Find the min and the max values from a baseline image mitk::ImageStatisticsHolder *stats = diffImage->GetStatistics(); //Initialize filter that calculates the modeled diffusion weighted signals FilterType::Pointer filter = FilterType::New(); filter->SetInput( tensorImage ); filter->SetBValue( static_cast(diffImage->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue()); filter->SetGradientList(gradients); filter->SetMin(stats->GetScalarValueMin()); filter->SetMax(stats->GetScalarValueMax()); filter->Update(); // TENSORS TO DATATREE mitk::Image::Pointer image = mitk::GrabItkImageMemory( filter->GetOutput() ); image->SetProperty( mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( gradients ) ); image->SetProperty( mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str(), mitk::FloatProperty::New( static_cast(diffImage->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ) ); image->SetProperty( mitk::DiffusionPropertyHelper::MEASUREMENTFRAMEPROPERTYNAME.c_str(), mitk::MeasurementFrameProperty::New( static_cast(diffImage->GetProperty(mitk::DiffusionPropertyHelper::MEASUREMENTFRAMEPROPERTYNAME.c_str()).GetPointer() )->GetMeasurementFrame() ) ); mitk::DiffusionPropertyHelper propertyHelper( image ); propertyHelper.InitializeImage(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); mitk::ImageVtkMapper2D::SetDefaultProperties(node); QString newname; newname = newname.append(nodename.c_str()); newname = newname.append("_Estimated DWI"); node->SetName(newname.toLatin1()); GetDefaultDataStorage()->Add(node, m_TensorImage); BValueMapType map = static_cast(image->GetProperty(mitk::DiffusionPropertyHelper::BVALUEMAPPROPERTYNAME.c_str()).GetPointer() )->GetBValueMap();; std::vector< unsigned int > b0Indices = map[0]; typedef itk::ResidualImageFilter ResidualImageFilterType; ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(diffImage, itkVectorImagePointer); ITKDiffusionImageType::Pointer itkSecondVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(image, itkSecondVectorImagePointer); ResidualImageFilterType::Pointer residualFilter = ResidualImageFilterType::New(); residualFilter->SetInput( itkVectorImagePointer ); residualFilter->SetSecondDiffusionImage( itkSecondVectorImagePointer ); residualFilter->SetGradients(gradients); residualFilter->SetB0Index(b0Indices[0]); residualFilter->SetB0Threshold(30); residualFilter->Update(); itk::Image::Pointer residualImage = itk::Image::New(); residualImage = residualFilter->GetOutput(); mitk::Image::Pointer mitkResImg = mitk::Image::New(); mitk::CastToMitkImage(residualImage, mitkResImg); stats = mitkResImg->GetStatistics(); float min = stats->GetScalarValueMin(); float max = stats->GetScalarValueMax(); mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetTableRange(min, max); // If you don't want to use the whole color range, you can use // SetValueRange, SetHueRange, and SetSaturationRange lookupTable->Build(); vtkSmartPointer reversedlookupTable = vtkSmartPointer::New(); reversedlookupTable->SetTableRange(min+1, max); reversedlookupTable->Build(); for(int i=0; i<256; i++) { double* rgba = reversedlookupTable->GetTableValue(255-i); lookupTable->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]); } lut->SetVtkLookupTable(lookupTable); lutProp->SetLookupTable(lut); // Create lookuptable mitk::DataNode::Pointer resNode=mitk::DataNode::New(); resNode->SetData( mitkResImg ); resNode->SetName("Residuals"); resNode->SetProperty("LookupTable", lutProp); bool b; resNode->GetBoolProperty("use color", b); resNode->SetBoolProperty("use color", false); GetDefaultDataStorage()->Add(resNode, m_TensorImage); m_MultiWidget->RequestUpdate(); // Draw Graph std::vector means = residualFilter->GetMeans(); std::vector q1s = residualFilter->GetQ1(); std::vector q3s = residualFilter->GetQ3(); std::vector percentagesOfOUtliers = residualFilter->GetPercentagesOfOutliers(); m_Controls->m_ResidualAnalysis->SetMeans(means); m_Controls->m_ResidualAnalysis->SetQ1(q1s); m_Controls->m_ResidualAnalysis->SetQ3(q3s); m_Controls->m_ResidualAnalysis->SetPercentagesOfOutliers(percentagesOfOUtliers); if(m_Controls->m_PercentagesOfOutliers->isChecked()) { m_Controls->m_ResidualAnalysis->DrawPercentagesOfOutliers(); } else { m_Controls->m_ResidualAnalysis->DrawMeans(); } // Draw Graph for volumes per slice in the QGraphicsView std::vector< std::vector > outliersPerSlice = residualFilter->GetOutliersPerSlice(); int xSize = outliersPerSlice.size(); if(xSize == 0) { return; } int ySize = outliersPerSlice[0].size(); // Find maximum in outliersPerSlice double maxOutlier= 0.0; for(int i=0; imaxOutlier) { maxOutlier = outliersPerSlice[i][j]; } } } // Create some QImage QImage qImage(xSize, ySize, QImage::Format_RGB32); QImage legend(1, 256, QImage::Format_RGB32); QRgb value; vtkSmartPointer lookup = vtkSmartPointer::New(); lookup->SetTableRange(0.0, maxOutlier); lookup->Build(); reversedlookupTable->SetTableRange(0, maxOutlier); reversedlookupTable->Build(); for(int i=0; i<256; i++) { double* rgba = reversedlookupTable->GetTableValue(255-i); lookup->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]); } // Fill qImage for(int i=0; iMapValue(out); int r, g, b; r = _rgba[0]; g = _rgba[1]; b = _rgba[2]; value = qRgb(r, g, b); qImage.setPixel(i,j,value); } } for(int i=0; i<256; i++) { double* rgba = lookup->GetTableValue(i); int r, g, b; r = rgba[0]*255; g = rgba[1]*255; b = rgba[2]*255; value = qRgb(r, g, b); legend.setPixel(0,255-i,value); } QString upper = QString::number(maxOutlier, 'g', 3); upper.append(" %"); QString lower = QString::number(0.0); lower.append(" %"); m_Controls->m_UpperLabel->setText(upper); m_Controls->m_LowerLabel->setText(lower); QPixmap pixmap(QPixmap::fromImage(qImage)); QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap); item->setTransform(QTransform::fromScale(10.0, 3.0), true); QPixmap pixmap2(QPixmap::fromImage(legend)); QGraphicsPixmapItem *item2 = new QGraphicsPixmapItem(pixmap2); item2->setTransform(QTransform::fromScale(20.0, 1.0), true); m_Controls->m_PerSliceView->SetResidualPixmapItem(item); QGraphicsScene* scene = new QGraphicsScene; QGraphicsScene* scene2 = new QGraphicsScene; scene->addItem(item); scene2->addItem(item2); m_Controls->m_PerSliceView->setScene(scene); m_Controls->m_LegendView->setScene(scene2); m_Controls->m_PerSliceView->show(); m_Controls->m_PerSliceView->repaint(); m_Controls->m_LegendView->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); m_Controls->m_LegendView->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); m_Controls->m_LegendView->show(); m_Controls->m_LegendView->repaint(); } void QmitkTensorReconstructionView::Reconstruct() { int method = m_Controls->m_ReconctructionMethodBox->currentIndex(); switch (method) { case 0: ItkTensorReconstruction(m_DiffusionImages); break; case 1: TensorReconstructionWithCorr(m_DiffusionImages); break; default: ItkTensorReconstruction(m_DiffusionImages); } } void QmitkTensorReconstructionView::TensorReconstructionWithCorr (mitk::DataStorage::SetOfObjects::Pointer inImages) { try { int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast((*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // TENSOR RECONSTRUCTION MITK_INFO << "Tensor reconstruction with correction for negative eigenvalues"; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Tensor reconstruction for %s", nodename.c_str()).toLatin1()); typedef itk::TensorReconstructionWithEigenvalueCorrectionFilter< DiffusionPixelType, TTensorPixelType > ReconstructionFilter; float b0Threshold = m_Controls->m_TensorReconstructionThreshold->value(); GradientDirectionContainerType::Pointer gradientContainerCopy = GradientDirectionContainerType::New(); for(GradientDirectionContainerType::ConstIterator it = static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer()->Begin(); it != static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer()->End(); it++) { gradientContainerCopy->push_back(it.Value()); } ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); ReconstructionFilter::Pointer reconFilter = ReconstructionFilter::New(); reconFilter->SetGradientImage( gradientContainerCopy, itkVectorImagePointer); reconFilter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); reconFilter->SetB0Threshold(b0Threshold); reconFilter->Update(); typedef itk::Image, 3> TensorImageType; TensorImageType::Pointer outputTensorImg = reconFilter->GetOutput(); typedef itk::ImageRegionIterator TensorImageIteratorType; TensorImageIteratorType tensorIt(outputTensorImg, outputTensorImg->GetRequestedRegion()); tensorIt.GoToBegin(); int negatives = 0; while(!tensorIt.IsAtEnd()) { typedef itk::DiffusionTensor3D TensorType; TensorType tensor = tensorIt.Get(); TensorType::EigenValuesArrayType ev; tensor.ComputeEigenValues(ev); for(unsigned int i=0; iInitializeByItk( outputTensorImg.GetPointer() ); image->SetVolume( outputTensorImg->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+"_EigenvalueCorrected_DT"); GetDefaultDataStorage()->Add(node, *itemiter); mitk::ProgressBar::GetInstance()->Progress(); ++itemiter; } mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); } } void QmitkTensorReconstructionView::ItkTensorReconstruction(mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // TENSOR RECONSTRUCTION clock.Start(); MITK_DEBUG << "Tensor reconstruction "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Tensor reconstruction for %s", nodename.c_str()).toLatin1()); typedef itk::DiffusionTensor3DReconstructionImageFilter< DiffusionPixelType, DiffusionPixelType, TTensorPixelType > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer tensorReconstructionFilter = TensorReconstructionImageFilterType::New(); GradientDirectionContainerType::Pointer gradientContainerCopy = GradientDirectionContainerType::New(); for(GradientDirectionContainerType::ConstIterator it = static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer()->Begin(); it != static_cast( vols->GetProperty(mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str()).GetPointer() )->GetGradientDirectionsContainer()->End(); it++) { gradientContainerCopy->push_back(it.Value()); } ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); tensorReconstructionFilter->SetGradientImage( gradientContainerCopy, itkVectorImagePointer ); tensorReconstructionFilter->SetBValue( static_cast(vols->GetProperty(mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str()).GetPointer() )->GetValue() ); tensorReconstructionFilter->SetThreshold( m_Controls->m_TensorReconstructionThreshold->value() ); tensorReconstructionFilter->Update(); clock.Stop(); MITK_DEBUG << "took " << clock.GetMean() << "s."; // TENSORS TO DATATREE mitk::TensorImage::Pointer image = mitk::TensorImage::New(); typedef itk::Image, 3> TensorImageType; TensorImageType::Pointer tensorImage; tensorImage = tensorReconstructionFilter->GetOutput(); // Check the tensor for negative eigenvalues if(m_Controls->m_CheckNegativeEigenvalues->isChecked()) { typedef itk::ImageRegionIterator TensorImageIteratorType; TensorImageIteratorType tensorIt(tensorImage, tensorImage->GetRequestedRegion()); tensorIt.GoToBegin(); while(!tensorIt.IsAtEnd()) { typedef itk::DiffusionTensor3D TensorType; //typedef itk::Tensor TensorType2; TensorType tensor = tensorIt.Get(); TensorType::EigenValuesArrayType ev; tensor.ComputeEigenValues(ev); for(unsigned int i=0; iSetDirection( itkVectorImagePointer->GetDirection() ); image->InitializeByItk( tensorImage.GetPointer() ); image->SetVolume( tensorReconstructionFilter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); SetDefaultNodeProperties(node, nodename+"_LinearLeastSquares_DT"); GetDefaultDataStorage()->Add(node, *itemiter); mitk::ProgressBar::GetInstance()->Progress(); ++itemiter; } mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "Reconstruction not possible:", ex.GetDescription()); return; } } void QmitkTensorReconstructionView::SetDefaultNodeProperties(mitk::DataNode::Pointer node, std::string name) { node->SetProperty( "ShowMaxNumber", mitk::IntProperty::New( 500 ) ); node->SetProperty( "Scaling", mitk::FloatProperty::New( 1.0 ) ); node->SetProperty( "Normalization", mitk::OdfNormalizationMethodProperty::New()); node->SetProperty( "ScaleBy", mitk::OdfScaleByProperty::New()); node->SetProperty( "IndexParam1", mitk::FloatProperty::New(2)); node->SetProperty( "IndexParam2", mitk::FloatProperty::New(1)); node->SetProperty( "visible", mitk::BoolProperty::New( true ) ); node->SetProperty( "VisibleOdfs", mitk::BoolProperty::New( false ) ); node->SetProperty ("layer", mitk::IntProperty::New(100)); node->SetProperty( "DoRefresh", mitk::BoolProperty::New( true ) ); node->SetProperty( "name", mitk::StringProperty::New(name) ); } void QmitkTensorReconstructionView::TensorsToDWI() { DoTensorsToDWI(m_TensorImages); } void QmitkTensorReconstructionView::TensorsToQbi() { for (unsigned int i=0; isize(); i++) { mitk::DataNode::Pointer tensorImageNode = m_TensorImages->at(i); MITK_INFO << "starting Q-Ball estimation"; typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; TensorImageType::Pointer itkvol = TensorImageType::New(); mitk::CastToItkImage(dynamic_cast(tensorImageNode->GetData()), itkvol); typedef itk::TensorImageToQBallImageFilter< TTensorPixelType, TTensorPixelType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( itkvol ); filter->Update(); typedef itk::Vector OutputPixelType; typedef itk::Image OutputImageType; mitk::QBallImage::Pointer image = mitk::QBallImage::New(); OutputImageType::Pointer outimg = filter->GetOutput(); image->InitializeByItk( outimg.GetPointer() ); image->SetVolume( outimg->GetBufferPointer() ); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName(tensorImageNode->GetName()+"_Qball"); GetDefaultDataStorage()->Add(node, tensorImageNode); } } void QmitkTensorReconstructionView::OnSelectionChanged( std::vector nodes ) { m_DiffusionImages = mitk::DataStorage::SetOfObjects::New(); m_TensorImages = mitk::DataStorage::SetOfObjects::New(); bool foundDwiVolume = false; bool foundTensorVolume = false; m_Controls->m_DiffusionImageLabel->setText("mandatory"); m_DiffusionImage = NULL; m_TensorImage = NULL; m_Controls->m_InputData->setTitle("Please Select Input Data"); // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNull()) continue; // only look at interesting types bool isDiffusionImage( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage( dynamic_cast(node->GetData())) ); if ( isDiffusionImage ) { foundDwiVolume = true; m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); m_DiffusionImages->push_back(node); m_DiffusionImage = node; } else if(dynamic_cast(node->GetData())) { foundTensorVolume = true; m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); m_TensorImages->push_back(node); m_TensorImage = node; } } m_Controls->m_StartReconstruction->setEnabled(foundDwiVolume); m_Controls->m_TensorsToDWIButton->setEnabled(foundTensorVolume); m_Controls->m_TensorsToQbiButton->setEnabled(foundTensorVolume); if (foundDwiVolume || foundTensorVolume) m_Controls->m_InputData->setTitle("Input Data"); m_Controls->m_ResidualButton->setEnabled(foundDwiVolume && foundTensorVolume); m_Controls->m_PercentagesOfOutliers->setEnabled(foundDwiVolume && foundTensorVolume); m_Controls->m_PerSliceView->setEnabled(foundDwiVolume && foundTensorVolume); } template itk::VectorContainer >::Pointer QmitkTensorReconstructionView::MakeGradientList() { itk::VectorContainer >::Pointer retval = itk::VectorContainer >::New(); vnl_matrix_fixed* U = itk::PointShell >::DistributePointShell(); for(int i=0; i v; v[0] = U->get(0,i); v[1] = U->get(1,i); v[2] = U->get(2,i); retval->push_back(v); } // Add 0 vector for B0 vnl_vector_fixed v; v.fill(0.0); retval->push_back(v); return retval; } void QmitkTensorReconstructionView::DoTensorsToDWI(mitk::DataStorage::SetOfObjects::Pointer inImages) { try { itk::TimeProbe clock; int nrFiles = inImages->size(); if (!nrFiles) return; QString status; mitk::ProgressBar::GetInstance()->AddStepsToDo(nrFiles); mitk::DataStorage::SetOfObjects::const_iterator itemiter( inImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( inImages->end() ); while ( itemiter != itemiterend ) // for all items { std::string nodename; (*itemiter)->GetStringProperty("name", nodename); mitk::TensorImage* vol = static_cast((*itemiter)->GetData()); typedef float TTensorPixelType; typedef itk::DiffusionTensor3D< TTensorPixelType > TensorPixelType; typedef itk::Image< TensorPixelType, 3 > TensorImageType; TensorImageType::Pointer itkvol = TensorImageType::New(); mitk::CastToItkImage(vol, itkvol); typedef itk::TensorImageToDiffusionImageFilter< TTensorPixelType, DiffusionPixelType > FilterType; FilterType::GradientListPointerType gradientList = FilterType::GradientListType::New(); switch(m_Controls->m_TensorsToDWINumDirsSelect->currentIndex()) { case 0: gradientList = MakeGradientList<12>(); break; case 1: gradientList = MakeGradientList<42>(); break; case 2: gradientList = MakeGradientList<92>(); break; case 3: gradientList = MakeGradientList<162>(); break; case 4: gradientList = MakeGradientList<252>(); break; case 5: gradientList = MakeGradientList<362>(); break; case 6: gradientList = MakeGradientList<492>(); break; case 7: gradientList = MakeGradientList<642>(); break; case 8: gradientList = MakeGradientList<812>(); break; case 9: gradientList = MakeGradientList<1002>(); break; default: gradientList = MakeGradientList<92>(); } double bVal = m_Controls->m_TensorsToDWIBValueEdit->text().toDouble(); // DWI ESTIMATION clock.Start(); MBI_INFO << "DWI Estimation "; mitk::StatusBar::GetInstance()->DisplayText(status.sprintf( "DWI Estimation for %s", nodename.c_str()).toLatin1()); FilterType::Pointer filter = FilterType::New(); filter->SetInput( itkvol ); filter->SetBValue(bVal); filter->SetGradientList(gradientList); //filter->SetNumberOfThreads(1); filter->Update(); clock.Stop(); MBI_DEBUG << "took " << clock.GetMean() << "s."; // TENSORS TO DATATREE mitk::Image::Pointer image = mitk::GrabItkImageMemory( filter->GetOutput() ); image->SetProperty( mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( gradientList ) ); image->SetProperty( mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str(), mitk::FloatProperty::New( bVal ) ); image->SetProperty( mitk::DiffusionPropertyHelper::MEASUREMENTFRAMEPROPERTYNAME.c_str(), mitk::MeasurementFrameProperty::New() ); mitk::DiffusionPropertyHelper propertyHelper( image ); propertyHelper.InitializeImage(); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( image ); mitk::ImageVtkMapper2D::SetDefaultProperties(node); node->SetName(nodename+"_DWI"); GetDefaultDataStorage()->Add(node, *itemiter); mitk::ProgressBar::GetInstance()->Progress(); ++itemiter; } mitk::StatusBar::GetInstance()->DisplayText(status.sprintf("Finished Processing %d Files", nrFiles).toLatin1()); m_MultiWidget->RequestUpdate(); } catch (itk::ExceptionObject &ex) { MITK_INFO << ex ; QMessageBox::information(0, "DWI estimation failed:", ex.GetDescription()); return ; } } void QmitkTensorReconstructionView::PreviewThreshold(int threshold) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_DiffusionImages->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_DiffusionImages->end() ); while ( itemiter != itemiterend ) // for all items { mitk::Image* vols = static_cast( (*itemiter)->GetData()); ITKDiffusionImageType::Pointer itkVectorImagePointer = ITKDiffusionImageType::New(); mitk::CastToItkImage(vols, itkVectorImagePointer); // Extract b0 image typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filterB0 = FilterType::New(); filterB0->SetInput(itkVectorImagePointer); filterB0->SetDirections(mitk::DiffusionPropertyHelper::GetGradientContainer(vols)); filterB0->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); typedef itk::Image ImageType; typedef itk::Image SegmentationType; typedef itk::BinaryThresholdImageFilter ThresholdFilterType; // apply threshold ThresholdFilterType::Pointer filterThreshold = ThresholdFilterType::New(); filterThreshold->SetInput(filterB0->GetOutput()); filterThreshold->SetLowerThreshold(threshold); filterThreshold->SetInsideValue(0); filterThreshold->SetOutsideValue(1); // mark cut off values red filterThreshold->Update(); mitkImage->InitializeByItk( filterThreshold->GetOutput() ); mitkImage->SetVolume( filterThreshold->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node; if (this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter)) { node = this->GetDefaultDataStorage()->GetNamedDerivedNode("ThresholdOverlay", *itemiter); } else { // create a new node, to show thresholded values node = mitk::DataNode::New(); GetDefaultDataStorage()->Add( node, *itemiter ); node->SetProperty( "name", mitk::StringProperty::New("ThresholdOverlay")); node->SetBoolProperty("helper object", true); } node->SetData( mitkImage ); itemiter++; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp index 2cab188697..418b1b9683 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.cpp @@ -1,85 +1,84 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionImagingAppWorkbenchAdvisor.h" #include "internal/QmitkDiffusionApplicationPlugin.h" #include #include #include -#include #include #include -const std::string QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; +const QString QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; void QmitkDiffusionImagingAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkDiffusionImagingAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { - std::vector perspExcludeList; - perspExcludeList.push_back( std::string("org.blueberry.uitest.util.EmptyPerspective") ); - perspExcludeList.push_back( std::string("org.blueberry.uitest.util.EmptyPerspective2") ); + QList perspExcludeList; + perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective" ); + perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective2" ); // perspExcludeList.push_back( std::string("org.mitk.coreapp.defaultperspective") ); //perspExcludeList.push_back( std::string("org.mitk.extapp.defaultperspective") ); - perspExcludeList.push_back( std::string("org.mitk.perspectives.publicdiffusionimaging") ); - perspExcludeList.push_back( std::string("org.mitk.perspectives.diffusionimaginginternal") ); + perspExcludeList.push_back( "org.mitk.perspectives.publicdiffusionimaging" ); + perspExcludeList.push_back("org.mitk.perspectives.diffusionimaginginternal" ); // Exclude the help perspective from org.blueberry.ui.qt.help from // the normal perspective list. // The perspective gets a dedicated menu entry in the help menu perspExcludeList.push_back("org.blueberry.perspectives.help"); - std::vector viewExcludeList; - viewExcludeList.push_back( std::string("org.mitk.views.controlvisualizationpropertiesview") ); - viewExcludeList.push_back( std::string("org.mitk.views.imagenavigator") ); + QList viewExcludeList; + viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview" ); + viewExcludeList.push_back( "org.mitk.views.imagenavigator" ); // viewExcludeList.push_back( std::string("org.mitk.views.datamanager") ); - viewExcludeList.push_back( std::string("org.mitk.views.modules") ); - viewExcludeList.push_back( std::string("org.blueberry.ui.internal.introview") ); + viewExcludeList.push_back( "org.mitk.views.modules" ); + viewExcludeList.push_back( "org.blueberry.ui.internal.introview" ); configurer->SetInitialSize(berry::Point(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->ShowViewMenuItem(true); advisor->ShowNewWindowMenuItem(true); advisor->ShowClosePerspectiveMenuItem(true); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowPerspectiveToolbar(false); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->ShowMemoryIndicator(false); advisor->SetProductName("MITK Diffusion"); advisor->SetWindowIcon(":/org.mitk.gui.qt.diffusionimagingapp/app-icon.png"); return advisor; } -std::string QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() +QString QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h index ae9646128b..401a392d24 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/QmitkDiffusionImagingAppWorkbenchAdvisor.h @@ -1,39 +1,39 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ #define QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ #include class QmitkDiffusionImagingAppWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.diffusionimagingapp.defaultperspective" + static const QString WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.diffusionimagingapp.defaultperspective" void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); - std::string GetInitialWindowPerspectiveId(); + QString GetInitialWindowPerspectiveId(); }; #endif /* QMITKDIFFUSIONIMAGINGAPPWORKBENCHADVISOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h index 9b8e79ef15..8a0befb4eb 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionApplicationPlugin.h @@ -1,55 +1,53 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ #define QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ #include #include -#include - -class QmitkDiffusionApplicationPlugin : public QObject, public berry::AbstractUICTKPlugin +class QmitkDiffusionApplicationPlugin : public berry::AbstractUICTKPlugin { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_diffusionimagingapp") #endif Q_INTERFACES(ctkPluginActivator) public: QmitkDiffusionApplicationPlugin(); ~QmitkDiffusionApplicationPlugin(); static QmitkDiffusionApplicationPlugin* GetDefault(); ctkPluginContext* GetPluginContext() const; void start(ctkPluginContext*); QString GetQtHelpCollectionFile() const; private: static QmitkDiffusionApplicationPlugin* inst; ctkPluginContext* context; }; #endif /* QMITKDIFFUSIONAPPLICATIONPLUGIN_H_ */ diff --git a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp index f527d82203..f614228b3b 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDiffusionImagingAppIntroPart.cpp @@ -1,212 +1,211 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionImagingAppIntroPart.h" #include "mitkNodePredicateDataType.h" #include #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include #include #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) # include #endif #include #include #include #include #include #include #include "QmitkDiffusionApplicationPlugin.h" #include "mitkDataStorageEditorInput.h" #include #include "mitkProgressBar.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" QmitkDiffusionImagingAppIntroPart::QmitkDiffusionImagingAppIntroPart() : m_Controls(NULL) { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkDiffusionImagingAppIntroPart::~QmitkDiffusionImagingAppIntroPart() { // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } else { berry::IPreferences::Pointer workbenchPrefs = QmitkDiffusionApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } // if workbench is not closing (Just welcome screen closing), open last used perspective if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId() == "org.mitk.diffusionimagingapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.perspectives.diffusiondefault"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } } void QmitkDiffusionImagingAppIntroPart::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkWelcomeScreenViewControls; m_Controls->setupUi(parent); // create a QWebView as well as a QWebPage and QWebFrame within the QWebview m_view = new QWebView(parent); m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdiffusionimagingappwelcomeview.html"), QUrl::TolerantMode ); m_view->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_view); this->CreateConnections(); } } void QmitkDiffusionImagingAppIntroPart::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) ); } } void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext) { QString scheme = showMeNext.scheme(); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QByteArray urlHostname = showMeNext.encodedHost(); QByteArray urlPath = showMeNext.encodedPath(); QByteArray dataset = showMeNext.encodedQueryItemValue("dataset"); QByteArray clear = showMeNext.encodedQueryItemValue("clear"); #else QByteArray urlHostname = QUrl::toAce(showMeNext.host()); QByteArray urlPath = showMeNext.path().toLatin1(); QUrlQuery query(showMeNext); QByteArray dataset = query.queryItemValue("dataset").toLatin1(); QByteArray clear = query.queryItemValue("clear").toLatin1();//showMeNext.encodedQueryItemValue("clear"); #endif if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ; // if the scheme is set to mitk, it is to be tested which action should be applied if (scheme.contains(QString("mitk")) ) { if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ; // searching for the perspective keyword within the host name if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); - QString tmpPerspectiveId(urlPath.data()); - tmpPerspectiveId.replace(QString("/"), QString("") ); - std::string perspectiveId = tmpPerspectiveId.toStdString(); + QString perspectiveId(urlPath.data()); + perspectiveId.replace(QString("/"), QString("") ); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); // search the Workbench for opened StdMultiWidgets to ensure the focus does not stay on the welcome screen and is switched to // an StdMultiWidget if one available - mitk::IDataStorageService::Pointer service = - berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); - berry::IEditorInput::Pointer editorInput; - editorInput = new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ); + mitk::IDataStorageService* service = this->GetIntroSite()->GetService(); + berry::IEditorInput::Pointer editorInput( + new mitk::DataStorageEditorInput( service->GetActiveDataStorage() )); // the solution is not clean, but the dependency to the StdMultiWidget was removed in order to fix a crash problem // as described in Bug #11715 // This is the correct way : use the static string ID variable // berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->FindEditors( editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID ); // QuickFix: we use the same string for an local variable - const std::string stdEditorID = "org.mitk.editors.stdmultiwidget"; + const QString stdEditorID = "org.mitk.editors.stdmultiwidget"; // search for opened StdMultiWidgetEditors - std::vector editorList = GetIntroSite()->GetPage()->FindEditors( editorInput, stdEditorID, 1 ); + QList editorList = GetIntroSite()->GetPage()->FindEditors( editorInput, stdEditorID, 1 ); // if an StdMultiWidgetEditor open was found, give focus to it - if(editorList.size()) + if(!editorList.isEmpty()) { GetIntroSite()->GetPage()->Activate( editorList[0]->GetPart(true) ); } } } // if the scheme is set to http, by default no action is performed, if an external webpage needs to be // shown it should be implemented below else if (scheme.contains(QString("http")) ) { QDesktopServices::openUrl(showMeNext); // m_view->load( ) ; } else if(scheme.contains("qrc")) { m_view->load(showMeNext); } } void QmitkDiffusionImagingAppIntroPart::StandbyStateChanged(bool) { } void QmitkDiffusionImagingAppIntroPart::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp index c99aa6de75..6caabbed42 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.cpp @@ -1,111 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) -Copyright (c) German Cancer Research Center, +Copyright (cGerman Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDTIAtlasAppWorkbenchAdvisor.h" #include "internal/QmitkDTIAtlasAppApplicationPlugin.h" #include #include +#include #include -#include + #include #include -const std::string QmitkDTIAtlasAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.dtiatlasapp.perspectives.welcome"; +const QString QmitkDTIAtlasAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.dtiatlasapp.perspectives.welcome"; void QmitkDTIAtlasAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); // TODO This should go into the products plugin_customization.ini file (when // the product and branding support is finished, see bug 2146). // This will not work anymore, if bug 2822 is fixed. - berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); prefService->GetSystemPreferences()->Put(berry::WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, berry::WorkbenchPreferenceConstants::RIGHT); - - QString collectionFile = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetQtHelpCollectionFile(); - if (!collectionFile.isEmpty()) - { -// berry::QtAssistantUtil::SetHelpCollectionFile(collectionFile); -// berry::QtAssistantUtil::SetDefaultHelpUrl("qthelp://org.mitk.gui.qt.dtiatlasapp/bundle/index.html"); - - typedef std::vector BundleContainer; - BundleContainer bundles = berry::Platform::GetBundles(); - berry::QtAssistantUtil::RegisterQCHFiles(bundles); - } - } berry::WorkbenchWindowAdvisor* QmitkDTIAtlasAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { - std::vector perspExcludeList; - perspExcludeList.push_back( std::string("org.mitk.dtiatlasapp.perspectives.welcome") ); - perspExcludeList.push_back( std::string("org.mitk.perspectives.diffusionimaginginternal") ); - perspExcludeList.push_back( std::string("org.mitk.perspectives.publicdiffusionimaging") ); - perspExcludeList.push_back( std::string("org.mitk.extapp.defaultperspective") ); - perspExcludeList.push_back( std::string("org.mitk.coreapp.defaultperspective") ); - - std::vector viewExcludeList; - viewExcludeList.push_back( std::string("org.mitk.views.partialvolumeanalysis") ); - viewExcludeList.push_back( std::string("org.mitk.views.globalfibertracking") ); - viewExcludeList.push_back( std::string("org.mitk.views.tractbasedspatialstatistics") ); - viewExcludeList.push_back( std::string("org.mitk.views.fibertracking") ); - viewExcludeList.push_back( std::string("org.mitk.views.ivim") ); - viewExcludeList.push_back( std::string("org.mitk.views.qballreconstruction") ); - viewExcludeList.push_back( std::string("org.mitk.views.diffusiondicomimport") ); - viewExcludeList.push_back( std::string("org.mitk.views.diffusionpreprocessing") ); - viewExcludeList.push_back( std::string("org.mitk.views.diffusionquantification") ); - viewExcludeList.push_back( std::string("org.mitk.views.tensorreconstruction") ); - viewExcludeList.push_back( std::string("org.mitk.views.perspectiveswitcher") ); - viewExcludeList.push_back( std::string("org.mitk.views.basicimageprocessing") ); - viewExcludeList.push_back( std::string("org.mitk.views.fiberbundleoperations") ); - viewExcludeList.push_back( std::string("org.mitk.views.measurement") ); - viewExcludeList.push_back( std::string("org.mitk.views.moviemaker") ); - viewExcludeList.push_back( std::string("org.mitk.views.odfdetails") ); - viewExcludeList.push_back( std::string("org.mitk.views.properties") ); - viewExcludeList.push_back( std::string("org.mitk.views.screenshotmaker") ); - viewExcludeList.push_back( std::string("org.mitk.views.segmentation") ); - viewExcludeList.push_back( std::string("org.mitk.views.imagestatistics") ); -// viewExcludeList.push_back( std::string("org.mitk.views.controlvisualizationpropertiesview") ); - viewExcludeList.push_back( std::string("org.mitk.views.volumevisualization") ); - viewExcludeList.push_back( std::string("org.mitk.views.simplemeasurement") ); + QList perspExcludeList; + perspExcludeList.push_back( "org.mitk.dtiatlasapp.perspectives.welcome"); + perspExcludeList.push_back( "org.mitk.perspectives.diffusionimaginginternal"); + perspExcludeList.push_back( "org.mitk.perspectives.publicdiffusionimaging"); + perspExcludeList.push_back( "org.mitk.extapp.defaultperspective"); + perspExcludeList.push_back( "org.mitk.coreapp.defaultperspective"); + + QList viewExcludeList; + viewExcludeList.push_back( "org.mitk.views.partialvolumeanalysis"); + viewExcludeList.push_back( "org.mitk.views.globalfibertracking"); + viewExcludeList.push_back( "org.mitk.views.tractbasedspatialstatistics"); + viewExcludeList.push_back( "org.mitk.views.fibertracking"); + viewExcludeList.push_back( "org.mitk.views.ivim"); + viewExcludeList.push_back( "org.mitk.views.qballreconstruction"); + viewExcludeList.push_back( "org.mitk.views.diffusiondicomimport"); + viewExcludeList.push_back( "org.mitk.views.diffusionpreprocessing"); + viewExcludeList.push_back( "org.mitk.views.diffusionquantification"); + viewExcludeList.push_back( "org.mitk.views.tensorreconstruction"); + viewExcludeList.push_back( "org.mitk.views.perspectiveswitcher"); + viewExcludeList.push_back( "org.mitk.views.basicimageprocessing"); + viewExcludeList.push_back( "org.mitk.views.fiberbundleoperations"); + viewExcludeList.push_back( "org.mitk.views.measurement"); + viewExcludeList.push_back( "org.mitk.views.moviemaker"); + viewExcludeList.push_back( "org.mitk.views.odfdetails"); + viewExcludeList.push_back( "org.mitk.views.properties"); + viewExcludeList.push_back( "org.mitk.views.screenshotmaker"); + viewExcludeList.push_back( "org.mitk.views.segmentation"); + viewExcludeList.push_back( "org.mitk.views.imagestatistics"); +// viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview"); + viewExcludeList.push_back( "org.mitk.views.volumevisualization"); + viewExcludeList.push_back( "org.mitk.views.simplemeasurement"); configurer->SetShowPerspectiveBar(false); configurer->SetInitialSize(berry::Point(1000,770)); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowVersionInfo(false); advisor->ShowMitkVersionInfo(false); advisor->SetProductName("based on MITK Diffusion Imaging App"); advisor->SetWindowIcon(":/org.mitk.gui.qt.dtiatlasapp/app-icon.png"); return advisor; } -std::string QmitkDTIAtlasAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() +QString QmitkDTIAtlasAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h index a16ec377df..a8998e1250 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/QmitkDTIAtlasAppWorkbenchAdvisor.h @@ -1,39 +1,39 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDTIATLASAPPWORKBENCHADVISOR_H_ #define QMITKDTIATLASAPPWORKBENCHADVISOR_H_ #include class QmitkDTIAtlasAppWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: - static const std::string WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.dtiatlasapp.defaultperspective" + static const QString WELCOME_PERSPECTIVE_ID; // = "org.mitk.qt.dtiatlasapp.defaultperspective" void Initialize(berry::IWorkbenchConfigurer::Pointer configurer); berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer); - std::string GetInitialWindowPerspectiveId(); + QString GetInitialWindowPerspectiveId(); }; #endif /* QMITKDTIATLASAPPWORKBENCHADVISOR_H_ */ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp index cbc6c6d0cc..8a2ccead57 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.cpp @@ -1,121 +1,110 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDTIAtlasAppApplicationPlugin.h" #include #include -#include #include "src/QmitkDTIAtlasAppApplication.h" #include "src/internal/QmitkDTIAtlasAppIntroPart.h" #include "src/internal/QmitkDTIAtlasAppPerspective.h" #include "src/internal/QmitkWelcomePerspective.h" #include #include QmitkDTIAtlasAppApplicationPlugin* QmitkDTIAtlasAppApplicationPlugin::inst = 0; QmitkDTIAtlasAppApplicationPlugin::QmitkDTIAtlasAppApplicationPlugin() - : pluginListener(0) { inst = this; } QmitkDTIAtlasAppApplicationPlugin::~QmitkDTIAtlasAppApplicationPlugin() { - delete pluginListener; } QmitkDTIAtlasAppApplicationPlugin* QmitkDTIAtlasAppApplicationPlugin::GetDefault() { return inst; } void QmitkDTIAtlasAppApplicationPlugin::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppApplication, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppIntroPart, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDTIAtlasAppPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkWelcomePerspective, context) // QString collectionFile = GetQtHelpCollectionFile(); // berry::QtAssistantUtil::SetHelpCollectionFile(collectionFile); // berry::QtAssistantUtil::SetDefaultHelpUrl("qthelp://org.mitk.gui.qt.dtiatlasapp/bundle/index.html"); - delete pluginListener; - pluginListener = new berry::QCHPluginListener(context); - context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); - - // register all QCH files from all the currently installed plugins - pluginListener->processPlugins(); - - } QString QmitkDTIAtlasAppApplicationPlugin::GetQtHelpCollectionFile() const { if (!helpCollectionFile.isEmpty()) { return helpCollectionFile; } QString collectionFilename; QString na("n/a"); // if (na != MITK_REVISION) // collectionFilename = "MitkDTIAtlasAppQtHelpCollection_" MITK_REVISION ".qhc"; // else collectionFilename = "MitkDTIAtlasAppQtHelpCollection.qhc"; QFileInfo collectionFileInfo = context->getDataFile(collectionFilename); QFileInfo pluginFileInfo = QFileInfo(QUrl(context->getPlugin()->getLocation()).toLocalFile()); if (!collectionFileInfo.exists() || pluginFileInfo.lastModified() > collectionFileInfo.lastModified()) { // extract the qhc file from the plug-in QByteArray content = context->getPlugin()->getResource(collectionFilename); if (content.isEmpty()) { BERRY_WARN << "Could not get plug-in resource: " << collectionFilename.toStdString(); } else { QFile file(collectionFileInfo.absoluteFilePath()); file.open(QIODevice::WriteOnly); file.write(content); file.close(); } } if (QFile::exists(collectionFileInfo.absoluteFilePath())) { helpCollectionFile = collectionFileInfo.absoluteFilePath(); } return helpCollectionFile; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_dtiatlasapp, QmitkDTIAtlasAppApplicationPlugin) #endif diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h index c7b74966c2..952d1378ab 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppApplicationPlugin.h @@ -1,60 +1,55 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ #define QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ #include #include -#include -#include - -class QmitkDTIAtlasAppApplicationPlugin : - public QObject, public berry::AbstractUICTKPlugin +class QmitkDTIAtlasAppApplicationPlugin : public berry::AbstractUICTKPlugin { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_dtiatlasapp") #endif Q_INTERFACES(ctkPluginActivator) public: QmitkDTIAtlasAppApplicationPlugin(); ~QmitkDTIAtlasAppApplicationPlugin(); static QmitkDTIAtlasAppApplicationPlugin* GetDefault(); ctkPluginContext* GetPluginContext() const; void start(ctkPluginContext*); QString GetQtHelpCollectionFile() const; private: static QmitkDTIAtlasAppApplicationPlugin* inst; ctkPluginContext* context; - berry::QCHPluginListener* pluginListener; mutable QString helpCollectionFile; }; // QmitkDTIAtlasAppApplicationPlugin #endif // QMITKDTIATLASAPPAPPLICATIONPLUGIN_H_ diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp index fdf78eaf3c..baf8a14ee9 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppIntroPart.cpp @@ -1,269 +1,268 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDTIAtlasAppIntroPart.h" #include "mitkNodePredicateDataType.h" #include #include #include #include #include #include +#include #include #include #include #include #include #include #include #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) # include #endif #include #include #include #include #include #include #include "QmitkStdMultiWidget.h" #include "QmitkStdMultiWidgetEditor.h" #include "QmitkDTIAtlasAppApplicationPlugin.h" #include "mitkDataStorageEditorInput.h" #include #include "mitkSceneIO.h" #include "mitkProgressBar.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" QmitkDTIAtlasAppIntroPart::QmitkDTIAtlasAppIntroPart() : m_Controls(NULL) { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } QmitkDTIAtlasAppIntroPart::~QmitkDTIAtlasAppIntroPart() { // if the workbench is not closing (that means, welcome screen was closed explicitly), set "Show_intro" false if (!this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } else { berry::IPreferences::Pointer workbenchPrefs = QmitkDTIAtlasAppApplicationPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); workbenchPrefs->PutBool(berry::WorkbenchPreferenceConstants::SHOW_INTRO, true); workbenchPrefs->Flush(); } // if workbench is not closing (Just welcome screen closing), open last used perspective if (this->GetIntroSite()->GetPage()->GetPerspective()->GetId() == "org.mitk.dtiatlasapp.perspectives.welcome" && !this->GetIntroSite()->GetPage()->GetWorkbenchWindow()->GetWorkbench()->IsClosing()) { berry::IPerspectiveDescriptor::Pointer perspective = this->GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->GetPerspectiveRegistry()->FindPerspectiveWithId("org.mitk.dtiatlasapp.perspectives.dtiatlasapp"); if (perspective) { this->GetIntroSite()->GetPage()->SetPerspective(perspective); } } } void QmitkDTIAtlasAppIntroPart::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkWelcomeScreenViewControls; m_Controls->setupUi(parent); // create a QWebView as well as a QWebPage and QWebFrame within the QWebview m_view = new QWebView(parent); m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); QUrl urlQtResource(QString("qrc:/org.mitk.gui.qt.welcomescreen/mitkdtiatlasappwelcomeview.html"), QUrl::TolerantMode ); m_view->load( urlQtResource ); // adds the webview as a widget parent->layout()->addWidget(m_view); this->CreateConnections(); } } void QmitkDTIAtlasAppIntroPart::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_view->page()), SIGNAL(linkClicked(const QUrl& )), this, SLOT(DelegateMeTo(const QUrl& )) ); } } void QmitkDTIAtlasAppIntroPart::DelegateMeTo(const QUrl& showMeNext) { QString scheme = showMeNext.scheme(); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QByteArray urlHostname = showMeNext.encodedHost(); QByteArray urlPath = showMeNext.encodedPath(); QByteArray dataset = showMeNext.encodedQueryItemValue("dataset"); QByteArray clear = showMeNext.encodedQueryItemValue("clear"); #else QByteArray urlHostname = QUrl::toAce(showMeNext.host()); QByteArray urlPath = showMeNext.path().toLatin1(); QUrlQuery query(showMeNext); QByteArray dataset = query.queryItemValue("dataset").toLatin1(); QByteArray clear = query.queryItemValue("clear").toLatin1();//showMeNext.encodedQueryItemValue("clear"); #endif if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ; // if the scheme is set to mitk, it is to be tested which action should be applied if (scheme.contains(QString("mitk")) ) { if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ; // searching for the perspective keyword within the host name if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); - QString tmpPerspectiveId(urlPath.data()); - tmpPerspectiveId.replace(QString("/"), QString("") ); - std::string perspectiveId = tmpPerspectiveId.toStdString(); + QString perspectiveId(urlPath.data()); + perspectiveId.replace(QString("/"), QString("") ); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID); QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor; mitk::DataStorage::Pointer dataStorage; if (editor.Cast().IsNull()) { editorInput = new mitk::DataStorageEditorInput(); dataStorage = editorInput->GetDataStorageReference()->GetDataStorage(); } else { multiWidgetEditor = editor.Cast(); multiWidgetEditor->GetStdMultiWidget()->RequestUpdate(); dataStorage = multiWidgetEditor->GetEditorInput().Cast()->GetDataStorageReference()->GetDataStorage(); } bool dsmodified = false; QString *fileName = new QString(dataset.data()); if ( fileName->right(5) == ".mitk" ) { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); QString *sClear = new QString(clear.data()); if ( sClear->right(4) == "true" ) { clearDataStorageFirst = true; } mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( fileName->toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); dsmodified = true; mitk::ProgressBar::GetInstance()->Progress(2); } else { mitk::IOUtil::Load(fileName->toStdString(),*(dataStorage.GetPointer())); } if(dataStorage.IsNotNull() && dsmodified) { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred); if(rs->Size() > 0) { // calculate bounding geometry of these nodes mitk::TimeGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } } } // searching for the load if(urlHostname.contains(QByteArray("perspectives")) ) { // the simplified method removes every whitespace // ( whitespace means any character for which the standard C++ isspace() method returns true) urlPath = urlPath.simplified(); - QString tmpPerspectiveId(urlPath.data()); - tmpPerspectiveId.replace(QString("/"), QString("") ); - std::string perspectiveId = tmpPerspectiveId.toStdString(); + QString perspectiveId(urlPath.data()); + perspectiveId.replace(QString("/"), QString("") ); // is working fine as long as the perspective id is valid, if not the application crashes GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() ); mitk::DataStorageEditorInput::Pointer editorInput; editorInput = new mitk::DataStorageEditorInput(); GetIntroSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID); } else { MITK_INFO << "Unkown mitk action keyword (see documentation for mitk links)" ; } } // if the scheme is set to http, by default no action is performed, if an external webpage needs to be // shown it should be implemented below else if (scheme.contains(QString("http")) ) { QDesktopServices::openUrl(showMeNext); // m_view->load( ) ; } else if(scheme.contains("qrc")) { m_view->load(showMeNext); } } void QmitkDTIAtlasAppIntroPart::StandbyStateChanged(bool standby) { } void QmitkDTIAtlasAppIntroPart::SetFocus() { } diff --git a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp index 4d928d7467..a8475249c4 100644 --- a/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.dtiatlasapp/src/internal/QmitkDTIAtlasAppPerspective.cpp @@ -1,89 +1,89 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDTIAtlasAppPerspective.h" #include "berryIViewLayout.h" void QmitkDTIAtlasAppPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", false, berry::IPageLayout::BOTTOM, .5f, "org.mitk.views.datamanager"); layout->AddStandaloneView("org.mitk.views.imagenavigator", false, berry::IPageLayout::BOTTOM, .8f, "org.mitk.views.controlvisualizationpropertiesview"); // berry::IFolderLayout::Pointer left = // layout->CreateFolder("org.mbi.diffusionimaginginternal.leftcontrols", // berry::IPageLayout::BOTTOM, 0.2f, "org.mitk.views.controlvisualizationpropertiesview"); // layout->AddStandaloneView("org.mitk.views.perspectiveswitcher", // false, berry::IPageLayout::BOTTOM, 0.99f, "org.mbi.diffusionimaginginternal.leftcontrols"); //////////////////////////////////////// // public views go here //////////////////////////////////////// // left->AddView("org.mitk.views.fiberbundleoperations"); // berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.fiberbundleoperations"); // lo->SetCloseable(false); // left->AddView("org.mitk.views.diffusionpreprocessing"); // berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.tensorreconstruction"); // lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.qballreconstruction"); // lo = layout->GetViewLayout("org.mitk.views.qballreconstruction"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.diffusionquantification"); // lo = layout->GetViewLayout("org.mitk.views.diffusionquantification"); // lo->SetCloseable(true); // left->AddView("org.mitk.views.diffusiondicomimport"); // lo = layout->GetViewLayout("org.mitk.views.diffusiondicomimport"); // lo->SetCloseable(true); //////////////////////////////////////// // end public views //////////////////////////////////////// // berry::IFolderLayout::Pointer right = // layout->CreateFolder("org.mbi.diffusionimaginginternal.rightcontrols", berry::IPageLayout::RIGHT, 0.5f, editorArea); //////////////////////////////////////// // internal views go here //////////////////////////////////////// // right->AddView("org.mitk.views.globalfibertracking"); // right->AddView("org.mitk.views.partialvolumeanalysis"); // right->AddView("org.mitk.views.ivim"); // right->AddView("org.mitk.views.tractbasedspatialstatistics"); // right->AddView("org.mitk.views.fibertracking"); //////////////////////////////////////// // end internal views //////////////////////////////////////// } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index 2a709f1be5..a311a0a566 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1355 +1,1355 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack * QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForViewNavigator: public berry::IPartListener { public: PartListenerForViewNavigator(QAction* act) : viewNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } private: QAction* viewNavigatorAction; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa), perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } //GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->viewNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { QList perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->viewNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer), lastInput(0), wbAdvisor(wbAdvisor), showViewToolbar(true), showPerspectiveToolbar(false), showVersionInfo(true), showMitkVersionInfo(true), showViewMenuItem(true), showNewWindowMenuItem(false), showClosePerspectiveMenuItem(true), viewNavigatorFound(false), showMemoryIndicator(true), dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName(); viewExcludeList.push_back("org.mitk.views.viewnavigatorview"); } QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor() { } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor( new QmitkExtActionBarAdvisor(configurer)); return actionBarAdvisor; } void* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(void* parent) { QWidget* parentWidget = static_cast(parent); QLabel* label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show) { showMemoryIndicator = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowMemoryIndicator() { return showMemoryIndicator; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const QString& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = qobject_cast (window->GetShell()->GetControl()); window->SetPerspectiveExcludeList(perspectiveExcludeList); window->SetViewExcludeList(viewExcludeList); if (!windowIcon.isEmpty()) { mainWindow->setWindowIcon(QIcon(windowIcon)); } mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); /*mainWindow->setStyleSheet("color: white;" "background-color: #808080;" "selection-color: #659EC7;" "selection-background-color: #808080;" " QMenuBar {" "background-color: #808080; }");*/ // Load selected icon theme QStringList searchPaths = QIcon::themeSearchPaths(); searchPaths.push_front( QString(":/org_mitk_icons/icons/") ); QIcon::setThemeSearchPaths( searchPaths ); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); - QString iconTheme = stylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>")); + QString iconTheme = stylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>"); if( iconTheme == QString( "<>" ) ) { iconTheme = QString( "tango" ); } QIcon::setThemeName( iconTheme ); // ==== Application menu ============================ /* QMenuBar* menuBar = mainWindow->menuBar(); menuBar->setContextMenuPolicy(Qt::PreventContextMenu); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->setObjectName("FileMenu"); QAction* fileOpenAction = new QmitkFileOpenAction(QIcon::fromTheme("document-open",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-open.svg")), window); fileOpenAction->setShortcut(QKeySequence::Open); fileMenu->addAction(fileOpenAction); QAction* fileSaveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.ext/Save_48.png"), window); fileSaveAction->setShortcut(QKeySequence::Save); fileMenu->addAction(fileSaveAction); fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(QIcon::fromTheme("document-save",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-save.svg"))); fileMenu->addAction(fileSaveProjectAction); closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(QIcon::fromTheme("edit-delete",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-delete.svg"))); fileMenu->addAction(closeProjectAction); fileMenu->addSeparator(); QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(QIcon::fromTheme("system-log-out",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/system-log-out.svg"))); fileExitAction->setShortcut(QKeySequence::Quit); fileExitAction->setObjectName("QmitkFileExitAction"); fileMenu->addAction(fileExitAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { openDicomEditorAction = new QmitkOpenDicomEditorAction(QIcon(":/org.mitk.gui.qt.ext/dcm-icon.png"),window); } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { openXnatEditorAction = new QmitkOpenXnatEditorAction(QIcon(":/org.mitk.gui.qt.ext/xnat-icon.png"),window); } berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); const QList viewDescriptors = viewRegistry->GetViews(); // another bad hack to get an edit/undo menu... QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(QIcon::fromTheme("edit-undo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-undo.svg")), "&Undo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), QKeySequence("CTRL+Z")); undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(QIcon::fromTheme("edit-redo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-redo.svg")) , "&Redo", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), QKeySequence("CTRL+Y")); redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if (imageNavigatorViewFound) { QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); imageNavigatorAction->setCheckable(true); // add part listener for image navigator imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); imageNavigatorAction->setChecked(false); if (imageNavigatorView) { bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) imageNavigatorAction->setChecked(true); } imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); } viewNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/view-manager_48.png"),"&View Navigator", NULL); viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigatorview"); if (viewNavigatorFound) { QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator())); viewNavigatorAction->setCheckable(true); // add part listener for view navigator viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction)); window->GetPartService()->AddPartListener(viewNavigatorPartListener.data()); berry::IViewPart::Pointer viewnavigatorview = window->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); viewNavigatorAction->setChecked(false); if (viewnavigatorview) { bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); if (isViewNavigatorVisible) viewNavigatorAction->setChecked(true); } viewNavigatorAction->setToolTip("Toggle View Navigator"); } // toolbar for showing file open, undo, redo and other main actions QToolBar* mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif mainActionsToolBar->addAction(fileOpenAction); mainActionsToolBar->addAction(fileSaveProjectAction); mainActionsToolBar->addAction(closeProjectAction); mainActionsToolBar->addAction(undoAction); mainActionsToolBar->addAction(redoAction); if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { mainActionsToolBar->addAction(openDicomEditorAction); } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { mainActionsToolBar->addAction(openXnatEditorAction); } if (imageNavigatorViewFound) { mainActionsToolBar->addAction(imageNavigatorAction); } if (viewNavigatorFound) mainActionsToolBar->addAction(viewNavigatorAction); mainWindow->addToolBar(mainActionsToolBar); #ifdef __APPLE__ #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) mainWindow->setUnifiedTitleAndToolBarOnMac(true); // default is false #endif #endif // ==== Window Menu ========================== QMenu* windowMenu = menuBar->addMenu("Window"); if (showNewWindowMenuItem) { windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); windowMenu->addSeparator(); } QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); QMenu* viewMenu; if (showViewMenuItem) { viewMenu = windowMenu->addMenu("Show &View"); viewMenu->setObjectName("Show View"); } windowMenu->addSeparator(); resetPerspAction = windowMenu->addAction("&Reset Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); if(showClosePerspectiveMenuItem) closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); windowMenu->addSeparator(); windowMenu->addAction("&Preferences...", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), QKeySequence("CTRL+P")); // fill perspective menu berry::IPerspectiveRegistry* perspRegistry = window->GetWorkbench()->GetPerspectiveRegistry(); QActionGroup* perspGroup = new QActionGroup(menuBar); QList perspectives( perspRegistry->GetPerspectives()); bool skip = false; for (QList::iterator perspIt = perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup); mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction); } perspMenu->addActions(perspGroup->actions()); // sort elements (converting vector to map...) QList::const_iterator iter; std::map VDMap; skip = false; for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { // if viewExcludeList is set, it contains the id-strings of view, which // should not appear as an menu-entry in the menu if (viewExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; if ((*iter)->GetId() == "org.mitk.views.imagenavigator") continue; if ((*iter)->GetId() == "org.mitk.views.viewnavigatorview") continue; std::pair p( (*iter)->GetLabel(), (*iter)); VDMap.insert(p); } // ==== Perspective Toolbar ================================== QToolBar* qPerspectiveToolbar = new QToolBar; qPerspectiveToolbar->setObjectName("perspectiveToolBar"); if (showPerspectiveToolbar) { qPerspectiveToolbar->addActions(perspGroup->actions()); mainWindow->addToolBar(qPerspectiveToolbar); } else delete qPerspectiveToolbar; // ==== View Toolbar ================================== QToolBar* qToolbar = new QToolBar; qToolbar->setObjectName("viewToolBar"); std::map::const_iterator MapIter; for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); viewActions.push_back(viewAction); if(showViewMenuItem) viewMenu->addAction(viewAction); if (showViewToolbar) { qToolbar->addAction(viewAction); } } if (showViewToolbar) { mainWindow->addToolBar(qToolbar); } else delete qToolbar; QSettings settings(GetQSettingsFile(), QSettings::IniFormat); mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); // ===== Help menu ==================================== QMenu* helpMenu = menuBar->addMenu("&Help"); helpMenu->addAction("&Welcome",this, SLOT(onIntro())); helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); helpMenu->addAction("&About",this, SLOT(onAbout())); // ===================================================== QStatusBar* qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); QmitkProgressBar *progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); // progBar->AddStepsToDo(2); // progBar->Progress(1); mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } */ } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this)); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data()); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener.data()); } void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen() { berry::WorkbenchWindowAdvisor::PostWindowOpen(); // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // get ImageNavigatorView berry::IViewPart::Pointer imageNavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); if (imageNavigatorView) { bool isImageNavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(imageNavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagenavigator"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator() { // get viewnavigatorView berry::IViewPart::Pointer viewnavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); if (viewnavigatorView) { bool isviewnavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(viewnavigatorView); if (isviewnavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(viewnavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.viewnavigatorview"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(0); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(NULL, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == 0) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),NULL); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); //titlePerspectiveListener = new PerspectiveListenerForTitle(this); editorPropertyListener.reset(new berry::PropertyChangeIntAdapter< QmitkExtWorkbenchWindowAdvisor>(this, &QmitkExtWorkbenchWindowAdvisor::PropertyChange)); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); //configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data()); } QString QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } QString title; //TODO Product // IProduct product = Platform.getProduct(); // if (product != null) { // title = product.getName(); // } // instead of the product name, we use a custom variable for now title = productName; if(showMitkVersionInfo) { title += QString(" ") + MITK_VERSION_STRING; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 VTK %4.%5.%6 Qt %7 MITK %8)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR) .arg(MITK_VERSION_STRING); title += versions; } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.isEmpty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); QString label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.isEmpty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); QString oldTitle = configurer->GetTitle(); QString newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = 0; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = 0; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } if (!lastActiveEditor.Expired()) { lastActiveEditor.Lock()->RemovePropertyListener(editorPropertyListener.data()); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener.data()); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { if (!lastActiveEditor.Expired()) { QString newTitle = lastActiveEditor.Lock()->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList& v) { this->perspectiveExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(const QList& v) { this->viewExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp index cac464238c..d753185e3a 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenXnatEditorAction.cpp @@ -1,81 +1,79 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkOpenXnatEditorAction.h" #include #include #include #include #include #include QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(berry::IWorkbenchWindow::Pointer window) : QAction(0) { this->init(window); } QmitkOpenXnatEditorAction::QmitkOpenXnatEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0) { this->setIcon(icon); this->init(window); } void QmitkOpenXnatEditorAction::init(berry::IWorkbenchWindow::Pointer window) { m_Window = window; this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&XNAT"); this->setToolTip("Open XNAT tool"); - berry::IPreferencesService::Pointer prefService - = berry::Platform::GetServiceRegistry() - .GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkOpenXnatEditorAction::Run() { // check if there is an open perspective, if not open the default perspective if (m_Window->GetActivePage().IsNull()) { - std::string defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); + QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window); } - std::vector editors = + QList editors = m_Window->GetActivePage()->FindEditors(berry::IEditorInput::Pointer(0), "org.mitk.editors.xnat.browser", berry::IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no XnatEditor is currently open, create a new one - berry::IEditorInput::Pointer editorInput(new berry::FileEditorInput(Poco::Path())); + berry::IEditorInput::Pointer editorInput(new berry::FileEditorInput(QString())); m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.xnat.browser"); } else { // reuse an existing editor berry::IEditorPart::Pointer reuseEditor = editors.front()->GetEditor(true); m_Window->GetActivePage()->Activate(reuseEditor); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp index 6e1f622a3c..dbf6158b82 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkExternalProgramsPreferencePage.cpp @@ -1,190 +1,188 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include -#include #include #include #include #include #include #include "QmitkExternalProgramsPreferencePage.h" static berry::IPreferences::Pointer GetPreferences() { - berry::IPreferencesService::Pointer preferencesService = - berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* preferencesService = berry::Platform::GetPreferencesService(); - if (preferencesService.IsNotNull()) + if (preferencesService != nullptr) { berry::IPreferences::Pointer systemPreferences = preferencesService->GetSystemPreferences(); if (systemPreferences.IsNotNull()) return systemPreferences->Node("/org.mitk.gui.qt.ext.externalprograms"); } mitkThrow(); } QmitkExternalProgramsPreferencePage::QmitkExternalProgramsPreferencePage() : m_Preferences(GetPreferences()), m_Ui(new Ui::QmitkExternalProgramsPreferencePage), m_Control(NULL), m_FFmpegProcess(NULL), m_GnuplotProcess(NULL) { } QmitkExternalProgramsPreferencePage::~QmitkExternalProgramsPreferencePage() { } void QmitkExternalProgramsPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_FFmpegProcess = new QProcess(m_Control); m_GnuplotProcess = new QProcess(m_Control); m_Ui->setupUi(m_Control); connect(m_FFmpegProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnFFmpegProcessError(QProcess::ProcessError))); connect(m_FFmpegProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnFFmpegProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->ffmpegButton, SIGNAL(clicked()), this, SLOT(OnFFmpegButtonClicked())); connect(m_GnuplotProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnGnuplotProcessError(QProcess::ProcessError))); connect(m_GnuplotProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnGnuplotProcessFinished(int, QProcess::ExitStatus))); connect(m_Ui->gnuplotButton, SIGNAL(clicked()), this, SLOT(OnGnuplotButtonClicked())); this->Update(); } void QmitkExternalProgramsPreferencePage::OnFFmpegButtonClicked() { QString filter = "ffmpeg/avconv executable "; #if defined(WIN32) filter += "(ffmpeg.exe avconv.exe)"; #else filter += "(ffmpeg avconv)"; #endif QString ffmpegPath = QFileDialog::getOpenFileName(m_Control, "FFmpeg/Libav", "", filter); if (!ffmpegPath.isEmpty()) { m_FFmpegPath = ffmpegPath; m_FFmpegProcess->start(ffmpegPath, QStringList() << "-version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessError(QProcess::ProcessError) { m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_FFmpegProcess->readAllStandardOutput()); if (output.startsWith("ffmpeg") || output.startsWith("avconv")) { m_Ui->ffmpegLineEdit->setText(m_FFmpegPath); return; } } m_FFmpegPath.clear(); m_Ui->ffmpegLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotButtonClicked() { QString filter = "gnuplot executable "; #if defined(WIN32) filter += "(gnuplot.exe)"; #else filter += "(gnuplot)"; #endif QString gnuplotPath = QFileDialog::getOpenFileName(m_Control, "Gnuplot", "", filter); if (!gnuplotPath.isEmpty()) { m_GnuplotPath = gnuplotPath; m_GnuplotProcess->start(gnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessError(QProcess::ProcessError) { m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } void QmitkExternalProgramsPreferencePage::OnGnuplotProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus == QProcess::NormalExit && exitCode == 0) { QString output = QTextCodec::codecForName("UTF-8")->toUnicode(m_GnuplotProcess->readAllStandardOutput()); if (output.startsWith("gnuplot")) { m_Ui->gnuplotLineEdit->setText(m_GnuplotPath); return; } } m_GnuplotPath.clear(); m_Ui->gnuplotLineEdit->clear(); } QWidget* QmitkExternalProgramsPreferencePage::GetQtControl() const { return m_Control; } void QmitkExternalProgramsPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkExternalProgramsPreferencePage::PerformCancel() { } bool QmitkExternalProgramsPreferencePage::PerformOk() { - m_Preferences->Put("ffmpeg", m_FFmpegPath.toStdString()); - m_Preferences->Put("gnuplot", m_GnuplotPath.toStdString()); + m_Preferences->Put("ffmpeg", m_FFmpegPath); + m_Preferences->Put("gnuplot", m_GnuplotPath); return true; } void QmitkExternalProgramsPreferencePage::Update() { - m_FFmpegPath = QString::fromStdString(m_Preferences->Get("ffmpeg", "")); + m_FFmpegPath = m_Preferences->Get("ffmpeg", ""); if (!m_FFmpegPath.isEmpty()) m_FFmpegProcess->start(m_FFmpegPath, QStringList() << "-version", QProcess::ReadOnly); - m_GnuplotPath = QString::fromStdString(m_Preferences->Get("gnuplot", "")); + m_GnuplotPath = m_Preferences->Get("gnuplot", ""); if (!m_GnuplotPath.isEmpty()) m_GnuplotProcess->start(m_GnuplotPath, QStringList() << "--version", QProcess::ReadOnly); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp index e3a2a1c4a4..c7d51f9fed 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/QmitkExtAppWorkbenchAdvisor.cpp @@ -1,61 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkExtAppWorkbenchAdvisor.h" #include "internal/QmitkExtApplicationPlugin.h" #include const QString QmitkExtAppWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.extapp.defaultperspective"; void QmitkExtAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkExtAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); // Exclude the help perspective from org.blueberry.ui.qt.help from // the normal perspective list. // The perspective gets a dedicated menu entry in the help menu QList excludePerspectives; excludePerspectives.push_back("org.blueberry.perspectives.help"); advisor->SetPerspectiveExcludeList(excludePerspectives); // Exclude some views from the normal view list - std::vector excludeViews; + QList excludeViews; excludeViews.push_back("org.mitk.views.modules"); excludeViews.push_back( "org.blueberry.ui.internal.introview" ); advisor->SetViewExcludeList(excludeViews); advisor->SetWindowIcon(":/org.mitk.gui.qt.extapplication/icon.png"); return advisor; //return new QmitkExtWorkbenchWindowAdvisor(this, configurer); } QString QmitkExtAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp index 3b8c837c01..9e68a6b335 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp @@ -1,22 +1,22 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkEditorPerspective.h" void QmitkEditorPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { - std::string editorArea = layout->GetEditorArea(); + layout->GetEditorArea(); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp index 1119c9c3ec..abb0201720 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp @@ -1,53 +1,53 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkVisualizationPerspective.h" #include "berryIViewLayout.h" void QmitkVisualizationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// - std::string editorArea = layout->GetEditorArea(); + QString editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mitk.extapplication.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.datamanager"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .4f, "org.mitk.extapplication.leftcontrols", true); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// left->AddView("org.mitk.views.volumevisualization"); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.volumevisualization"); lo->SetCloseable(true); left->AddView("org.mitk.views.screenshotmaker"); lo = layout->GetViewLayout("org.mitk.views.screenshotmaker"); lo->SetCloseable(true); left->AddView("org.mitk.views.moviemaker"); lo = layout->GetViewLayout("org.mitk.views.moviemaker"); lo->SetCloseable(true); } diff --git a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp index f4a991ac74..b232e9a42d 100644 --- a/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp +++ b/Plugins/org.mitk.gui.qt.igttracking/src/internal/QmitkMITKIGTTrackingToolboxView.cpp @@ -1,1346 +1,1346 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkMITKIGTTrackingToolboxView.h" #include "QmitkStdMultiWidget.h" // Qt #include #include #include // MITK #include #include #include #include #include #include #include #include #include #include #include #include // vtk #include //for exceptions #include #include const std::string QmitkMITKIGTTrackingToolboxView::VIEW_ID = "org.mitk.views.mitkigttrackingtoolbox"; QmitkMITKIGTTrackingToolboxView::QmitkMITKIGTTrackingToolboxView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) { m_TrackingTimer = new QTimer(this); m_TimeoutTimer = new QTimer(this); m_tracking = false; m_connected = false; m_logging = false; m_loggedFrames = 0; //create filename for autosaving of tool storage QString loggingPathWithoutFilename = QString(mitk::LoggingBackend::GetLogFile().c_str()); if (!loggingPathWithoutFilename.isEmpty()) //if there already is a path for the MITK logging file use this one { //extract path from path+filename (if someone knows a better way to do this feel free to change it) - int lengthOfFilename = Poco::Path(mitk::LoggingBackend::GetLogFile()).getFileName().size(); + int lengthOfFilename = QFileInfo(QString::fromStdString(mitk::LoggingBackend::GetLogFile())).fileName().size(); loggingPathWithoutFilename.resize(loggingPathWithoutFilename.size()-lengthOfFilename); m_AutoSaveFilename = loggingPathWithoutFilename + "TrackingToolboxAutoSave.IGTToolStorage"; } else //if not: use a temporary path from IOUtil { m_AutoSaveFilename = QString(mitk::IOUtil::GetTempPath().c_str()) + "TrackingToolboxAutoSave.IGTToolStorage"; } MITK_INFO("IGT Tracking Toolbox") << "Filename for auto saving of IGT ToolStorages: " << m_AutoSaveFilename.toStdString(); //initialize worker thread m_WorkerThread = new QThread(); m_Worker = new QmitkMITKIGTTrackingToolboxViewWorker(); } QmitkMITKIGTTrackingToolboxView::~QmitkMITKIGTTrackingToolboxView() { this->StoreUISettings(); m_TrackingTimer->stop(); m_TimeoutTimer->stop(); delete m_TrackingTimer; delete m_TimeoutTimer; try { // wait for thread to finish m_WorkerThread->terminate(); m_WorkerThread->wait(); //clean up worker thread if(m_WorkerThread) {delete m_WorkerThread;} if(m_Worker) {delete m_Worker;} //remove the tracking volume this->GetDataStorage()->Remove(m_TrackingVolumeNode); //remove the tool storage if(m_toolStorage) {m_toolStorage->UnRegisterMicroservice();} if(m_TrackingDeviceSource) {m_TrackingDeviceSource->UnRegisterMicroservice();} } catch(std::exception& e) {MITK_WARN << "Unexpected exception during clean up of tracking toolbox view: " << e.what();} catch(...) {MITK_WARN << "Unexpected unknown error during clean up of tracking toolbox view!";} //store tool storage and UI settings for persistence this->AutoSaveToolStorage(); this->StoreUISettings(); } void QmitkMITKIGTTrackingToolboxView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkMITKIGTTrackingToolboxViewControls; m_Controls->setupUi( parent ); //create connections connect( m_Controls->m_LoadTools, SIGNAL(clicked()), this, SLOT(OnLoadTools()) ); connect( m_Controls->m_ConnectDisconnectButton, SIGNAL(clicked()), this, SLOT(OnConnectDisconnect()) ); connect( m_Controls->m_StartStopTrackingButton, SIGNAL(clicked()), this, SLOT(OnStartStopTracking()) ); connect( m_TrackingTimer, SIGNAL(timeout()), this, SLOT(UpdateTrackingTimer())); connect( m_TimeoutTimer, SIGNAL(timeout()), this, SLOT(OnTimeOut())); connect( m_Controls->m_ChooseFile, SIGNAL(clicked()), this, SLOT(OnChooseFileClicked())); connect( m_Controls->m_StartLogging, SIGNAL(clicked()), this, SLOT(StartLogging())); connect( m_Controls->m_StopLogging, SIGNAL(clicked()), this, SLOT(StopLogging())); connect( m_Controls->m_VolumeSelectionBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(OnTrackingVolumeChanged(QString))); connect( m_Controls->m_ShowTrackingVolume, SIGNAL(clicked()), this, SLOT(OnShowTrackingVolumeChanged())); connect( m_Controls->m_AutoDetectTools, SIGNAL(clicked()), this, SLOT(OnAutoDetectTools())); connect( m_Controls->m_ResetTools, SIGNAL(clicked()), this, SLOT(OnResetTools())); connect( m_Controls->m_AddSingleTool, SIGNAL(clicked()), this, SLOT(OnAddSingleTool())); connect( m_Controls->m_NavigationToolCreationWidget, SIGNAL(NavigationToolFinished()), this, SLOT(OnAddSingleToolFinished())); connect( m_Controls->m_NavigationToolCreationWidget, SIGNAL(Canceled()), this, SLOT(OnAddSingleToolCanceled())); connect( m_Controls->m_csvFormat, SIGNAL(clicked()), this, SLOT(OnToggleFileExtension())); connect( m_Controls->m_xmlFormat, SIGNAL(clicked()), this, SLOT(OnToggleFileExtension())); //connections for the tracking device configuration widget connect( m_Controls->m_configurationWidget, SIGNAL(TrackingDeviceSelectionChanged()), this, SLOT(OnTrackingDeviceChanged())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressStarted()), this, SLOT(DisableOptionsButtons())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressStarted()), this, SLOT(DisableTrackingConfigurationButtons())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressStarted()), this, SLOT(DisableTrackingControls())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressFinished()), this, SLOT(EnableOptionsButtons())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressFinished()), this, SLOT(EnableTrackingConfigurationButtons())); connect( m_Controls->m_configurationWidget, SIGNAL(ProgressFinished()), this, SLOT(EnableTrackingControls())); //connect worker thread connect(m_Worker, SIGNAL(AutoDetectToolsFinished(bool,QString)), this, SLOT(OnAutoDetectToolsFinished(bool,QString)) ); connect(m_Worker, SIGNAL(ConnectDeviceFinished(bool,QString)), this, SLOT(OnConnectFinished(bool,QString)) ); connect(m_Worker, SIGNAL(StartTrackingFinished(bool,QString)), this, SLOT(OnStartTrackingFinished(bool,QString)) ); connect(m_Worker, SIGNAL(StopTrackingFinished(bool,QString)), this, SLOT(OnStopTrackingFinished(bool,QString)) ); connect(m_Worker, SIGNAL(DisconnectDeviceFinished(bool,QString)), this, SLOT(OnDisconnectFinished(bool,QString)) ); connect(m_WorkerThread,SIGNAL(started()), m_Worker, SLOT(ThreadFunc()) ); //move the worker to the thread m_Worker->moveToThread(m_WorkerThread); //initialize widgets m_Controls->m_configurationWidget->EnableAdvancedUserControl(false); m_Controls->m_TrackingToolsStatusWidget->SetShowPositions(true); m_Controls->m_TrackingToolsStatusWidget->SetTextAlignment(Qt::AlignLeft); //initialize tracking volume node m_TrackingVolumeNode = mitk::DataNode::New(); m_TrackingVolumeNode->SetName("TrackingVolume"); m_TrackingVolumeNode->SetBoolProperty("Backface Culling",true); mitk::Color red; red.SetRed(1); m_TrackingVolumeNode->SetColor(red); //initialize buttons m_Controls->m_AutoDetectTools->setVisible(false); //only visible if tracking device is Aurora m_Controls->m_StartStopTrackingButton->setEnabled(false); //Update List of available models for selected tool. std::vector Compatibles; if ( (m_Controls == NULL) || //check all these stuff for NULL, latterly this causes crashes from time to time (m_Controls->m_configurationWidget == NULL) || (m_Controls->m_configurationWidget->GetTrackingDevice().IsNull())) { MITK_ERROR << "Couldn't get current tracking device or an object is NULL, something went wrong!"; return; } else { Compatibles = mitk::GetDeviceDataForLine( m_Controls->m_configurationWidget->GetTrackingDevice()->GetType()); } m_Controls->m_VolumeSelectionBox->clear(); - for(int i = 0; i < Compatibles.size(); i++) + for(std::size_t i = 0; i < Compatibles.size(); i++) { m_Controls->m_VolumeSelectionBox->addItem(Compatibles[i].Model.c_str()); } //initialize tool storage m_toolStorage = mitk::NavigationToolStorage::New(GetDataStorage()); m_toolStorage->SetName("TrackingToolbox Default Storage"); m_toolStorage->RegisterAsMicroservice("no tracking device"); //set home directory as default path for logfile m_Controls->m_LoggingFileName->setText(QDir::toNativeSeparators(QDir::homePath()) + QDir::separator() + "logfile.csv"); //tracking device may be changed already by the persistence of the //QmitkTrackingDeciveConfigurationWidget this->OnTrackingDeviceChanged(); this->LoadUISettings(); //add tracking volume node only to data storage this->GetDataStorage()->Add(m_TrackingVolumeNode); if (!m_Controls->m_ShowTrackingVolume->isChecked()) m_TrackingVolumeNode->SetOpacity(0.0); else m_TrackingVolumeNode->SetOpacity(0.25); //Update List of available models for selected tool. m_Controls->m_VolumeSelectionBox->clear(); - for(int i = 0; i < Compatibles.size(); i++) + for(std::size_t i = 0; i < Compatibles.size(); i++) { m_Controls->m_VolumeSelectionBox->addItem(Compatibles[i].Model.c_str()); } } } void QmitkMITKIGTTrackingToolboxView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKIGTTrackingToolboxView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkMITKIGTTrackingToolboxView::OnLoadTools() { //read in filename QString filename = QFileDialog::getOpenFileName(NULL,tr("Open Tool Storage"), "/", tr("Tool Storage Files (*.IGTToolStorage)")); if (filename.isNull()) return; //read tool storage from disk std::string errorMessage = ""; mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(GetDataStorage()); // try-catch block for exceptions try { this->ReplaceCurrentToolStorage(myDeserializer->Deserialize(filename.toStdString()),filename.toStdString()); } catch(mitk::IGTException) { std::string errormessage = "Error during loading the tool storage file. Please only load tool storage files created with the NavigationToolManager view."; QMessageBox::warning(NULL, "Tool Storage Loading Error", errormessage.c_str()); return; } if(m_toolStorage->isEmpty()) { errorMessage = myDeserializer->GetErrorMessage(); MessageBox(errorMessage); return; } //update label UpdateToolStorageLabel(filename); //update tool preview m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); //save filename for persistent storage m_ToolStorageFilename = filename; } void QmitkMITKIGTTrackingToolboxView::OnResetTools() { this->ReplaceCurrentToolStorage(mitk::NavigationToolStorage::New(GetDataStorage()),"TrackingToolbox Default Storage"); m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); QString toolLabel = QString(""); m_Controls->m_toolLabel->setText(toolLabel); m_ToolStorageFilename = ""; } void QmitkMITKIGTTrackingToolboxView::OnStartStopTracking() { if(!m_connected) { MITK_WARN << "Can't start tracking if no device is connected. Aborting"; return; } if(m_tracking) {OnStopTracking();} else {OnStartTracking();} } void QmitkMITKIGTTrackingToolboxView::OnConnectDisconnect() { if(m_connected) {OnDisconnect();} else {OnConnect();} } void QmitkMITKIGTTrackingToolboxView::OnConnect() { MITK_INFO << "Connect Clicked"; //check if everything is ready to start tracking if (this->m_toolStorage.IsNull()) { MessageBox("Error: No Tools Loaded Yet!"); return; } else if (this->m_toolStorage->GetToolCount() == 0) { MessageBox("Error: No Way To Track Without Tools!"); return; } //parse tracking device data mitk::TrackingDeviceData data = mitk::DeviceDataUnspecified; QString qstr = m_Controls->m_VolumeSelectionBox->currentText(); if ( (! qstr.isNull()) || (! qstr.isEmpty()) ) { std::string str = qstr.toStdString(); data = mitk::GetDeviceDataByName(str); //Data will be set later, after device generation } //initialize worker thread m_Worker->SetWorkerMethod(QmitkMITKIGTTrackingToolboxViewWorker::eConnectDevice); m_Worker->SetTrackingDevice(this->m_Controls->m_configurationWidget->GetTrackingDevice()); m_Worker->SetInverseMode(m_Controls->m_InverseMode->isChecked()); m_Worker->SetNavigationToolStorage(this->m_toolStorage); m_Worker->SetTrackingDeviceData(data); //start worker thread m_WorkerThread->start(); //disable buttons this->m_Controls->m_MainWidget->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::OnConnectFinished(bool success, QString errorMessage) { m_WorkerThread->quit(); m_WorkerThread->wait(); //enable buttons this->m_Controls->m_MainWidget->setEnabled(true); if (!success) { MITK_WARN << errorMessage.toStdString(); MessageBox(errorMessage.toStdString()); return; } //get data from worker thread m_TrackingDeviceSource = m_Worker->GetTrackingDeviceSource(); m_TrackingDeviceData = m_Worker->GetTrackingDeviceData(); m_ToolVisualizationFilter = m_Worker->GetToolVisualizationFilter(); //enable/disable Buttons DisableOptionsButtons(); DisableTrackingConfigurationButtons(); m_Controls->m_configurationWidget->ConfigurationFinished(); m_Controls->m_TrackingControlLabel->setText("Status: connected"); m_Controls->m_ConnectDisconnectButton->setText("Disconnect"); m_Controls->m_StartStopTrackingButton->setEnabled(true); m_connected = true; } void QmitkMITKIGTTrackingToolboxView::OnDisconnect() { m_Worker->SetWorkerMethod(QmitkMITKIGTTrackingToolboxViewWorker::eDisconnectDevice); m_WorkerThread->start(); m_Controls->m_MainWidget->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::OnDisconnectFinished(bool success, QString errorMessage) { m_WorkerThread->quit(); m_WorkerThread->wait(); m_Controls->m_MainWidget->setEnabled(true); if (!success) { MITK_WARN << errorMessage.toStdString(); MessageBox(errorMessage.toStdString()); return; } //enable/disable Buttons m_Controls->m_StartStopTrackingButton->setEnabled(false); EnableOptionsButtons(); EnableTrackingConfigurationButtons(); m_Controls->m_configurationWidget->Reset(); m_Controls->m_TrackingControlLabel->setText("Status: disconnected"); m_Controls->m_ConnectDisconnectButton->setText("Connect"); m_connected = false; } void QmitkMITKIGTTrackingToolboxView::OnStartTracking() { m_Worker->SetWorkerMethod(QmitkMITKIGTTrackingToolboxViewWorker::eStartTracking); m_WorkerThread->start(); this->m_Controls->m_MainWidget->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::OnStartTrackingFinished(bool success, QString errorMessage) { m_WorkerThread->quit(); m_WorkerThread->wait(); this->m_Controls->m_MainWidget->setEnabled(true); if(!success) { MessageBox(errorMessage.toStdString()); MITK_WARN << errorMessage.toStdString(); return; } m_TrackingTimer->start(1000/(m_Controls->m_UpdateRate->value())); m_Controls->m_TrackingControlLabel->setText("Status: tracking"); //connect the tool visualization widget - for(int i=0; iGetNumberOfOutputs(); i++) + for(std::size_t i=0; iGetNumberOfOutputs(); i++) { m_Controls->m_TrackingToolsStatusWidget->AddNavigationData(m_TrackingDeviceSource->GetOutput(i)); } m_Controls->m_TrackingToolsStatusWidget->ShowStatusLabels(); if (m_Controls->m_ShowToolQuaternions->isChecked()) {m_Controls->m_TrackingToolsStatusWidget->SetShowQuaternions(true);} else {m_Controls->m_TrackingToolsStatusWidget->SetShowQuaternions(false);} //show tracking volume this->OnTrackingVolumeChanged(m_Controls->m_VolumeSelectionBox->currentText()); m_tracking = true; m_Controls->m_ConnectDisconnectButton->setEnabled(false); m_Controls->m_StartStopTrackingButton->setText("Stop Tracking"); this->GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnStopTracking() { if (!m_tracking) return; m_TrackingTimer->stop(); m_Worker->SetWorkerMethod(QmitkMITKIGTTrackingToolboxViewWorker::eStopTracking); m_WorkerThread->start(); m_Controls->m_MainWidget->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::OnStopTrackingFinished(bool success, QString errorMessage) { m_WorkerThread->quit(); m_WorkerThread->wait(); m_Controls->m_MainWidget->setEnabled(true); if(!success) { MessageBox(errorMessage.toStdString()); MITK_WARN << errorMessage.toStdString(); return; } m_Controls->m_TrackingControlLabel->setText("Status: connected"); if (m_logging) StopLogging(); m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); m_tracking = false; m_Controls->m_StartStopTrackingButton->setText("Start Tracking"); m_Controls->m_ConnectDisconnectButton->setEnabled(true); this->GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnTrackingDeviceChanged() { mitk::TrackingDeviceType Type; if (m_Controls->m_configurationWidget->GetTrackingDevice().IsNotNull()) { Type = m_Controls->m_configurationWidget->GetTrackingDevice()->GetType(); //enable controls because device is valid m_Controls->m_TrackingToolsGoupBox->setEnabled(true); m_Controls->m_TrackingControlsGroupBox->setEnabled(true); } else { Type = mitk::TrackingSystemNotSpecified; MessageBox("Error: This tracking device is not included in this project. Please make sure that the device is installed and activated in your MITK build."); m_Controls->m_TrackingToolsGoupBox->setEnabled(false); m_Controls->m_TrackingControlsGroupBox->setEnabled(false); return; } // Code to enable/disable device specific buttons if (Type == mitk::NDIAurora) //Aurora { m_Controls->m_AutoDetectTools->setVisible(true); m_Controls->m_AddSingleTool->setEnabled(false); } else //Polaris or Microntracker { m_Controls->m_AutoDetectTools->setVisible(false); m_Controls->m_AddSingleTool->setEnabled(true); } // Code to select appropriate tracking volume for current type std::vector Compatibles = mitk::GetDeviceDataForLine(Type); m_Controls->m_VolumeSelectionBox->clear(); - for(int i = 0; i < Compatibles.size(); i++) + for(std::size_t i = 0; i < Compatibles.size(); i++) { m_Controls->m_VolumeSelectionBox->addItem(Compatibles[i].Model.c_str()); } } void QmitkMITKIGTTrackingToolboxView::OnTrackingVolumeChanged(QString qstr) { if (qstr.isNull()) return; if (qstr.isEmpty()) return; mitk::TrackingVolumeGenerator::Pointer volumeGenerator = mitk::TrackingVolumeGenerator::New(); std::string str = qstr.toStdString(); mitk::TrackingDeviceData data = mitk::GetDeviceDataByName(str); m_TrackingDeviceData = data; volumeGenerator->SetTrackingDeviceData(data); volumeGenerator->Update(); mitk::Surface::Pointer volumeSurface = volumeGenerator->GetOutput(); m_TrackingVolumeNode->SetData(volumeSurface); if (!m_Controls->m_ShowTrackingVolume->isChecked()) m_TrackingVolumeNode->SetOpacity(0.0); else m_TrackingVolumeNode->SetOpacity(0.25); GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnShowTrackingVolumeChanged() { if (m_Controls->m_ShowTrackingVolume->isChecked()) { OnTrackingVolumeChanged(m_Controls->m_VolumeSelectionBox->currentText()); m_TrackingVolumeNode->SetOpacity(0.25); } else { m_TrackingVolumeNode->SetOpacity(0.0); } } void QmitkMITKIGTTrackingToolboxView::OnAutoDetectTools() { if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() == mitk::NDIAurora) { DisableTrackingConfigurationButtons(); m_Worker->SetWorkerMethod(QmitkMITKIGTTrackingToolboxViewWorker::eAutoDetectTools); m_Worker->SetTrackingDevice(m_Controls->m_configurationWidget->GetTrackingDevice().GetPointer()); m_Worker->SetDataStorage(this->GetDataStorage()); m_WorkerThread->start(); m_TimeoutTimer->start(5000); MITK_INFO << "Timeout Timer started"; //disable controls until worker thread is finished this->m_Controls->m_MainWidget->setEnabled(false); } } void QmitkMITKIGTTrackingToolboxView::OnAutoDetectToolsFinished(bool success, QString errorMessage) { m_TimeoutTimer->stop(); m_WorkerThread->quit(); m_WorkerThread->wait(); //enable controls again this->m_Controls->m_MainWidget->setEnabled(true); EnableTrackingConfigurationButtons(); if(!success) { MITK_WARN << errorMessage.toStdString(); MessageBox(errorMessage.toStdString()); EnableTrackingConfigurationButtons(); return; } mitk::NavigationToolStorage::Pointer autoDetectedStorage = m_Worker->GetNavigationToolStorage(); //save detected tools this->ReplaceCurrentToolStorage(autoDetectedStorage,"Autodetected NDI Aurora Storage"); //auto save the new storage to hard disc (for persistence) AutoSaveToolStorage(); //update label QString toolLabel = QString("Loaded Tools: ") + QString::number(m_toolStorage->GetToolCount()) + " Tools (Auto Detected)"; m_Controls->m_toolLabel->setText(toolLabel); //update tool preview m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); EnableTrackingConfigurationButtons(); if (m_toolStorage->GetToolCount()>0) { //ask the user if he wants to save the detected tools QMessageBox msgBox; switch(m_toolStorage->GetToolCount()) { case 1: msgBox.setText("Found one tool!"); break; default: msgBox.setText("Found " + QString::number(m_toolStorage->GetToolCount()) + " tools!"); } msgBox.setInformativeText("Do you want to save this tools as tool storage, so you can load them again?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); if (ret == 16384) //yes { //ask the user for a filename QString fileName = QFileDialog::getSaveFileName(NULL, tr("Save File"),"/",tr("*.IGTToolStorage")); //check for empty filename if(fileName == "") {return;} mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New(); //when Serialize method is used exceptions are thrown, need to be adapted //try-catch block for exception handling in Serializer try { mySerializer->Serialize(fileName.toStdString(),m_toolStorage); } catch(mitk::IGTException) { std::string errormessage = "Error during serialization. Please check the Zip file."; QMessageBox::warning(NULL, "IGTPlayer: Error", errormessage.c_str()); } return; } else if (ret == 65536) //no { return; } } //print a logging message about the detected tools switch(m_toolStorage->GetToolCount()) { case 0: MITK_INFO("IGT Tracking Toolbox") << "Found no tools. Empty ToolStorage was autosaved to " << m_ToolStorageFilename.toStdString(); break; case 1: MITK_INFO("IGT Tracking Toolbox") << "Found one tool. ToolStorage was autosaved to " << m_ToolStorageFilename.toStdString(); break; default: MITK_INFO("IGT Tracking Toolbox") << "Found " << m_toolStorage->GetToolCount() << " tools. ToolStorage was autosaved to " << m_ToolStorageFilename.toStdString(); } } void QmitkMITKIGTTrackingToolboxView::MessageBox(std::string s) { QMessageBox msgBox; msgBox.setText(s.c_str()); msgBox.exec(); } void QmitkMITKIGTTrackingToolboxView::UpdateTrackingTimer() { //update filter m_ToolVisualizationFilter->Update(); MITK_DEBUG << "Number of outputs ToolVisualizationFilter: " << m_ToolVisualizationFilter->GetNumberOfIndexedOutputs(); MITK_DEBUG << "Number of inputs ToolVisualizationFilter: " << m_ToolVisualizationFilter->GetNumberOfIndexedInputs(); //update tool colors to show tool status - for(int i=0; iGetNumberOfIndexedOutputs(); i++) + for(unsigned int i=0; iGetNumberOfIndexedOutputs(); i++) { mitk::NavigationData::Pointer currentTool = m_ToolVisualizationFilter->GetOutput(i); if(currentTool->IsDataValid()) {this->m_toolStorage->GetTool(i)->GetDataNode()->SetColor(mitk::IGTColor_VALID);} else {this->m_toolStorage->GetTool(i)->GetDataNode()->SetColor(mitk::IGTColor_WARNING);} } //update logging if (m_logging) { this->m_loggingFilter->Update(); m_loggedFrames = this->m_loggingFilter->GetNumberOfRecordedSteps(); this->m_Controls->m_LoggedFramesLabel->setText("Logged Frames: "+QString::number(m_loggedFrames)); //check if logging stopped automatically if((m_loggedFrames>1)&&(!m_loggingFilter->GetRecording())){StopLogging();} } //refresh view and status widget mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_Controls->m_TrackingToolsStatusWidget->Refresh(); //code to better isolate bug 17713, could be removed when bug 17713 is fixed static int i = 0; static mitk::Point3D lastPositionTool1 = m_ToolVisualizationFilter->GetOutput(0)->GetPosition(); static itk::TimeStamp lastTimeStamp = m_ToolVisualizationFilter->GetOutput(0)->GetTimeStamp(); i++; //every 20 frames: check if tracking is frozen if(i>20) { i = 0; if (m_ToolVisualizationFilter->GetOutput(0)->IsDataValid()) { if (mitk::Equal(lastPositionTool1,m_ToolVisualizationFilter->GetOutput(0)->GetPosition(),0.000000001,false)) { MITK_WARN << "Seems as tracking (of at least tool 1) is frozen which means that bug 17713 occurred. Restart tracking might help."; //display further information to find the bug MITK_WARN << "Timestamp of current navigation data: " << m_ToolVisualizationFilter->GetOutput(0)->GetTimeStamp(); MITK_WARN << "Timestamp of last navigation data (which holds the same values): " << lastTimeStamp; } lastPositionTool1 = m_ToolVisualizationFilter->GetOutput(0)->GetPosition(); lastTimeStamp = m_ToolVisualizationFilter->GetOutput(0)->GetTimeStamp(); } } } void QmitkMITKIGTTrackingToolboxView::OnChooseFileClicked() { QDir currentPath = QFileInfo(m_Controls->m_LoggingFileName->text()).dir(); // if no path was selected (QDir would select current working dir then) or the // selected path does not exist -> use home directory if ( currentPath == QDir() || ! currentPath.exists() ) { currentPath = QDir(QDir::homePath()); } QString filename = QFileDialog::getSaveFileName(NULL,tr("Choose Logging File"), currentPath.absolutePath(), "*.*"); if (filename == "") return; this->m_Controls->m_LoggingFileName->setText(filename); this->OnToggleFileExtension(); } // bug-16470: toggle file extension after clicking on radio button void QmitkMITKIGTTrackingToolboxView::OnToggleFileExtension() { QString currentInputText = this->m_Controls->m_LoggingFileName->text(); QString currentFile = QFileInfo(currentInputText).baseName(); QDir currentPath = QFileInfo(currentInputText).dir(); if(currentFile.isEmpty()) { currentFile = "logfile"; } // Setting currentPath to default home path when currentPath is empty or it does not exist if(currentPath == QDir() || !currentPath.exists()) { currentPath = QDir::homePath(); } // check if csv radio button is clicked if(this->m_Controls->m_csvFormat->isChecked()) { // you needn't add a seperator to the input text when currentpath is the rootpath if(currentPath.isRoot()) { this->m_Controls->m_LoggingFileName->setText(QDir::toNativeSeparators(currentPath.absolutePath()) + currentFile + ".csv"); } else { this->m_Controls->m_LoggingFileName->setText(QDir::toNativeSeparators(currentPath.absolutePath()) + QDir::separator() + currentFile + ".csv"); } } // check if xml radio button is clicked else if(this->m_Controls->m_xmlFormat->isChecked()) { // you needn't add a seperator to the input text when currentpath is the rootpath if(currentPath.isRoot()) { this->m_Controls->m_LoggingFileName->setText(QDir::toNativeSeparators(currentPath.absolutePath()) + currentFile + ".xml"); } else { this->m_Controls->m_LoggingFileName->setText(QDir::toNativeSeparators(currentPath.absolutePath()) + QDir::separator() + currentFile + ".xml"); } } } void QmitkMITKIGTTrackingToolboxView::StartLogging() { if (m_ToolVisualizationFilter.IsNull()) { MessageBox("Cannot activate logging without a connected device. Configure and connect a tracking device first."); return; } if (!m_logging) { //initialize logging filter m_loggingFilter = mitk::NavigationDataRecorder::New(); m_loggingFilter->ConnectTo(m_ToolVisualizationFilter); if (m_Controls->m_LoggingLimit->isChecked()){m_loggingFilter->SetRecordCountLimit(m_Controls->m_LoggedFramesLimit->value());} //start filter with try-catch block for exceptions try { m_loggingFilter->StartRecording(); } catch(mitk::IGTException) { std::string errormessage = "Error during start recording. Recorder already started recording?"; QMessageBox::warning(NULL, "IGTPlayer: Error", errormessage.c_str()); m_loggingFilter->StopRecording(); return; } //update labels / logging variables this->m_Controls->m_LoggingLabel->setText("Logging ON"); this->m_Controls->m_LoggedFramesLabel->setText("Logged Frames: 0"); m_loggedFrames = 0; m_logging = true; DisableLoggingButtons(); } } void QmitkMITKIGTTrackingToolboxView::StopLogging() { if (m_logging) { //stop logging m_loggingFilter->StopRecording(); m_logging = false; //update GUI this->m_Controls->m_LoggingLabel->setText("Logging OFF"); EnableLoggingButtons(); //write the results to a file if(m_Controls->m_csvFormat->isChecked()) { mitk::NavigationDataSetWriterCSV* writer = new mitk::NavigationDataSetWriterCSV(); writer->Write(this->m_Controls->m_LoggingFileName->text().toStdString(),m_loggingFilter->GetNavigationDataSet()); delete writer; } else if (m_Controls->m_xmlFormat->isChecked()) { mitk::NavigationDataSetWriterXML* writer = new mitk::NavigationDataSetWriterXML(); writer->Write(this->m_Controls->m_LoggingFileName->text().toStdString(),m_loggingFilter->GetNavigationDataSet()); delete writer; } } } void QmitkMITKIGTTrackingToolboxView::OnAddSingleTool() { QString Identifier = "Tool#"; if (m_toolStorage.IsNotNull()) Identifier += QString::number(m_toolStorage->GetToolCount()); else Identifier += "0"; m_Controls->m_NavigationToolCreationWidget->Initialize(GetDataStorage(),Identifier.toStdString()); m_Controls->m_NavigationToolCreationWidget->SetTrackingDeviceType(m_Controls->m_configurationWidget->GetTrackingDevice()->GetType(),false); m_Controls->m_TrackingToolsWidget->setCurrentIndex(1); //disable tracking volume during tool editing lastTrackingVolumeState = m_Controls->m_ShowTrackingVolume->isChecked(); if (lastTrackingVolumeState) m_Controls->m_ShowTrackingVolume->click(); GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnAddSingleToolFinished() { m_Controls->m_TrackingToolsWidget->setCurrentIndex(0); if (this->m_toolStorage.IsNull()) { //this shouldn't happen! MITK_WARN << "No ToolStorage available, cannot add tool, aborting!"; return; } m_toolStorage->AddTool(m_Controls->m_NavigationToolCreationWidget->GetCreatedTool()); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); m_Controls->m_toolLabel->setText(""); //auto save current storage for persistence MITK_INFO << "Auto saving manually added tools for persistence."; AutoSaveToolStorage(); //enable tracking volume again if (lastTrackingVolumeState) m_Controls->m_ShowTrackingVolume->click(); GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::OnAddSingleToolCanceled() { m_Controls->m_TrackingToolsWidget->setCurrentIndex(0); //enable tracking volume again if (lastTrackingVolumeState) m_Controls->m_ShowTrackingVolume->click(); GlobalReinit(); } void QmitkMITKIGTTrackingToolboxView::GlobalReinit() { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } void QmitkMITKIGTTrackingToolboxView::DisableLoggingButtons() { m_Controls->m_StartLogging->setEnabled(false); m_Controls->m_LoggingFileName->setEnabled(false); m_Controls->m_ChooseFile->setEnabled(false); m_Controls->m_LoggingLimit->setEnabled(false); m_Controls->m_LoggedFramesLimit->setEnabled(false); m_Controls->m_csvFormat->setEnabled(false); m_Controls->m_xmlFormat->setEnabled(false); m_Controls->m_StopLogging->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::EnableLoggingButtons() { m_Controls->m_StartLogging->setEnabled(true); m_Controls->m_LoggingFileName->setEnabled(true); m_Controls->m_ChooseFile->setEnabled(true); m_Controls->m_LoggingLimit->setEnabled(true); m_Controls->m_LoggedFramesLimit->setEnabled(true); m_Controls->m_csvFormat->setEnabled(true); m_Controls->m_xmlFormat->setEnabled(true); m_Controls->m_StopLogging->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::DisableOptionsButtons() { m_Controls->m_ShowTrackingVolume->setEnabled(false); m_Controls->m_UpdateRate->setEnabled(false); m_Controls->m_ShowToolQuaternions->setEnabled(false); m_Controls->m_OptionsUpdateRateLabel->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::EnableOptionsButtons() { m_Controls->m_ShowTrackingVolume->setEnabled(true); m_Controls->m_UpdateRate->setEnabled(true); m_Controls->m_ShowToolQuaternions->setEnabled(true); m_Controls->m_OptionsUpdateRateLabel->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::EnableTrackingControls() { m_Controls->m_TrackingControlsGroupBox->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::DisableTrackingControls() { m_Controls->m_TrackingControlsGroupBox->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::EnableTrackingConfigurationButtons() { m_Controls->m_AutoDetectTools->setEnabled(true); if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() != mitk::NDIAurora) m_Controls->m_AddSingleTool->setEnabled(true); m_Controls->m_LoadTools->setEnabled(true); m_Controls->m_ResetTools->setEnabled(true); } void QmitkMITKIGTTrackingToolboxView::DisableTrackingConfigurationButtons() { m_Controls->m_AutoDetectTools->setEnabled(false); if (m_Controls->m_configurationWidget->GetTrackingDevice()->GetType() != mitk::NDIAurora) m_Controls->m_AddSingleTool->setEnabled(false); m_Controls->m_LoadTools->setEnabled(false); m_Controls->m_ResetTools->setEnabled(false); } void QmitkMITKIGTTrackingToolboxView::ReplaceCurrentToolStorage(mitk::NavigationToolStorage::Pointer newStorage, std::string newStorageName) { //first: get rid of the old one //don't reset if there is no tool storage. BugFix #17793 if ( m_toolStorage.IsNotNull() ){ m_toolStorage->UnLockStorage(); //only to be sure... m_toolStorage->UnRegisterMicroservice(); m_toolStorage = NULL; } //now: replace by the new one m_toolStorage = newStorage; m_toolStorage->SetName(newStorageName); m_toolStorage->RegisterAsMicroservice("no tracking device"); } void QmitkMITKIGTTrackingToolboxView::OnTimeOut() { MITK_INFO << "Time Out"; m_WorkerThread->terminate(); m_WorkerThread->wait(); m_TimeoutTimer->stop(); } void QmitkMITKIGTTrackingToolboxView::StoreUISettings() { // persistence service does not directly work in plugins for now // -> using QSettings QSettings settings; settings.beginGroup(QString::fromStdString(VIEW_ID)); // set the values of some widgets and attrbutes to the QSettings settings.setValue("ShowTrackingVolume", QVariant(m_Controls->m_ShowTrackingVolume->isChecked())); settings.setValue("toolStorageFilename", QVariant(m_ToolStorageFilename)); settings.setValue("VolumeSelectionBox", QVariant(m_Controls->m_VolumeSelectionBox->currentIndex())); settings.endGroup(); } void QmitkMITKIGTTrackingToolboxView::LoadUISettings() { // persistence service does not directly work in plugins for now // -> using QSettings QSettings settings; settings.beginGroup(QString::fromStdString(VIEW_ID)); // set some widgets and attributes by the values from the QSettings m_Controls->m_ShowTrackingVolume->setChecked(settings.value("ShowTrackingVolume", true).toBool()); m_Controls->m_VolumeSelectionBox->setCurrentIndex(settings.value("VolumeSelectionBox", 0).toInt()); m_ToolStorageFilename = settings.value("toolStorageFilename", QVariant("")).toString(); settings.endGroup(); // try to deserialize the tool storage from the given tool storage file name if ( ! m_ToolStorageFilename.isEmpty() ) { // try-catch block for exceptions try { mitk::NavigationToolStorageDeserializer::Pointer myDeserializer = mitk::NavigationToolStorageDeserializer::New(GetDataStorage()); m_toolStorage->UnRegisterMicroservice(); m_toolStorage = myDeserializer->Deserialize(m_ToolStorageFilename.toStdString()); m_toolStorage->RegisterAsMicroservice("no tracking device"); //update label UpdateToolStorageLabel(m_ToolStorageFilename); //update tool preview m_Controls->m_TrackingToolsStatusWidget->RemoveStatusLabels(); m_Controls->m_TrackingToolsStatusWidget->PreShowTools(m_toolStorage); } catch(mitk::IGTException) { MITK_WARN("QmitkMITKIGTTrackingToolBoxView") << "Error during restoring tools. Problems with file ("<OnResetTools(); //if there where errors reset the tool storage to avoid problems later on } } } void QmitkMITKIGTTrackingToolboxView::UpdateToolStorageLabel(QString pathOfLoadedStorage) { - Poco::Path myPath = Poco::Path(pathOfLoadedStorage.toStdString()); //use this to seperate filename from path - QString toolLabel = myPath.getFileName().c_str(); + QFileInfo myPath(pathOfLoadedStorage); //use this to seperate filename from path + QString toolLabel = myPath.fileName(); if (toolLabel.size() > 45) //if the tool storage name is to long trimm the string { toolLabel.resize(40); toolLabel+="[...]"; } m_Controls->m_toolLabel->setText(toolLabel); } void QmitkMITKIGTTrackingToolboxView::AutoSaveToolStorage() { m_ToolStorageFilename = m_AutoSaveFilename; mitk::NavigationToolStorageSerializer::Pointer mySerializer = mitk::NavigationToolStorageSerializer::New(); mySerializer->Serialize(m_ToolStorageFilename.toStdString(),m_toolStorage); } void QmitkMITKIGTTrackingToolboxViewWorker::SetWorkerMethod(WorkerMethod w) { m_WorkerMethod = w; } void QmitkMITKIGTTrackingToolboxViewWorker::SetTrackingDevice(mitk::TrackingDevice::Pointer t) { m_TrackingDevice = t; } void QmitkMITKIGTTrackingToolboxViewWorker::SetDataStorage(mitk::DataStorage::Pointer d) { m_DataStorage = d; } void QmitkMITKIGTTrackingToolboxViewWorker::SetInverseMode(bool mode) { m_InverseMode = mode; } void QmitkMITKIGTTrackingToolboxViewWorker::SetTrackingDeviceData(mitk::TrackingDeviceData d) { m_TrackingDeviceData = d; } void QmitkMITKIGTTrackingToolboxViewWorker::SetNavigationToolStorage(mitk::NavigationToolStorage::Pointer n) { m_NavigationToolStorage = n; } void QmitkMITKIGTTrackingToolboxViewWorker::ThreadFunc() { switch(m_WorkerMethod) { case eAutoDetectTools: this->AutoDetectTools(); break; case eConnectDevice: this->ConnectDevice(); break; case eStartTracking: this->StartTracking(); break; case eStopTracking: this->StopTracking(); break; case eDisconnectDevice: this->DisconnectDevice(); break; default: MITK_WARN << "Undefined worker method was set ... something went wrong!"; break; } } void QmitkMITKIGTTrackingToolboxViewWorker::AutoDetectTools() { mitk::ProgressBar::GetInstance()->AddStepsToDo(4); mitk::NavigationToolStorage::Pointer autoDetectedStorage = mitk::NavigationToolStorage::New(m_DataStorage); mitk::NDITrackingDevice::Pointer currentDevice = dynamic_cast(m_TrackingDevice.GetPointer()); try { currentDevice->OpenConnection(); mitk::ProgressBar::GetInstance()->Progress(); currentDevice->StartTracking(); } catch(mitk::Exception& e) { QString message = QString("Warning, can not auto-detect tools! (") + QString(e.GetDescription()) + QString(")"); //MessageBox(message.toStdString()); //TODO: give message to the user here! MITK_WARN << message.toStdString(); mitk::ProgressBar::GetInstance()->Progress(4); emit AutoDetectToolsFinished(false,message.toStdString().c_str()); return; } - for (int i=0; iGetToolCount(); i++) + for (unsigned int i=0; iGetToolCount(); i++) { //create a navigation tool with sphere as surface std::stringstream toolname; toolname << "AutoDetectedTool" << i; mitk::NavigationTool::Pointer newTool = mitk::NavigationTool::New(); newTool->SetSerialNumber(dynamic_cast(currentDevice->GetTool(i))->GetSerialNumber()); newTool->SetIdentifier(toolname.str()); newTool->SetTrackingDeviceType(mitk::NDIAurora); mitk::DataNode::Pointer newNode = mitk::DataNode::New(); mitk::Surface::Pointer mySphere = mitk::Surface::New(); vtkSphereSource *vtkData = vtkSphereSource::New(); vtkData->SetRadius(3.0f); vtkData->SetCenter(0.0, 0.0, 0.0); vtkData->Update(); mySphere->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); newNode->SetData(mySphere); newNode->SetName(toolname.str()); newTool->SetDataNode(newNode); autoDetectedStorage->AddTool(newTool); } m_NavigationToolStorage = autoDetectedStorage; currentDevice->StopTracking(); mitk::ProgressBar::GetInstance()->Progress(); currentDevice->CloseConnection(); emit AutoDetectToolsFinished(true,""); mitk::ProgressBar::GetInstance()->Progress(4); } void QmitkMITKIGTTrackingToolboxViewWorker::ConnectDevice() { std::string message = ""; mitk::ProgressBar::GetInstance()->AddStepsToDo(10); //build the IGT pipeline mitk::TrackingDevice::Pointer trackingDevice = m_TrackingDevice; trackingDevice->SetData(m_TrackingDeviceData); //set device to rotation mode transposed becaus we are working with VNL style quaternions if(m_InverseMode) {trackingDevice->SetRotationMode(mitk::TrackingDevice::RotationTransposed);} //Get Tracking Volume Data mitk::TrackingDeviceData data = m_TrackingDeviceData; mitk::ProgressBar::GetInstance()->Progress(); //Create Navigation Data Source with the factory class mitk::TrackingDeviceSourceConfigurator::Pointer myTrackingDeviceSourceFactory = mitk::TrackingDeviceSourceConfigurator::New(m_NavigationToolStorage,trackingDevice); m_TrackingDeviceSource = myTrackingDeviceSourceFactory->CreateTrackingDeviceSource(m_ToolVisualizationFilter); mitk::ProgressBar::GetInstance()->Progress(); if ( m_TrackingDeviceSource.IsNull() ) { message = std::string("Cannot connect to device: ") + myTrackingDeviceSourceFactory->GetErrorMessage(); emit ConnectDeviceFinished(false,QString(message.c_str())); return; } //set filter to rotation mode transposed becaus we are working with VNL style quaternions if(m_InverseMode) m_ToolVisualizationFilter->SetRotationMode(mitk::NavigationDataObjectVisualizationFilter::RotationTransposed); //First check if the created object is valid if (m_TrackingDeviceSource.IsNull()) { message = myTrackingDeviceSourceFactory->GetErrorMessage(); emit ConnectDeviceFinished(false,QString(message.c_str())); return; } MITK_INFO << "Number of tools: " << m_TrackingDeviceSource->GetNumberOfOutputs(); mitk::ProgressBar::GetInstance()->Progress(); //The tools are maybe reordered after initialization, e.g. in case of auto-detected tools of NDI Aurora mitk::NavigationToolStorage::Pointer toolsInNewOrder = myTrackingDeviceSourceFactory->GetUpdatedNavigationToolStorage(); if ((toolsInNewOrder.IsNotNull()) && (toolsInNewOrder->GetToolCount() > 0)) { //so delete the old tools in wrong order and add them in the right order //we cannot simply replace the tool storage because the new storage is //not correctly initialized with the right data storage /* m_NavigationToolStorage->DeleteAllTools(); for (int i=0; i < toolsInNewOrder->GetToolCount(); i++) {m_NavigationToolStorage->AddTool(toolsInNewOrder->GetTool(i));} This was replaced and thereby fixed Bug 18318 DeleteAllTools() is not Threadsafe! */ for(int i = 0; i < toolsInNewOrder->GetToolCount(); i++ ) { m_NavigationToolStorage->AssignToolNumber(toolsInNewOrder->GetTool(i)->GetIdentifier(),i); } } mitk::ProgressBar::GetInstance()->Progress(); //connect to device try { m_TrackingDeviceSource->Connect(); mitk::ProgressBar::GetInstance()->Progress(); //Microservice registration: m_TrackingDeviceSource->RegisterAsMicroservice(); m_NavigationToolStorage->UnRegisterMicroservice(); m_NavigationToolStorage->RegisterAsMicroservice(m_TrackingDeviceSource->GetMicroserviceID()); m_NavigationToolStorage->LockStorage(); } catch (...) //todo: change to mitk::IGTException { message = "Error on connecting the tracking device."; emit ConnectDeviceFinished(false,QString(message.c_str())); return; } emit ConnectDeviceFinished(true,QString(message.c_str())); mitk::ProgressBar::GetInstance()->Progress(10); } void QmitkMITKIGTTrackingToolboxViewWorker::StartTracking() { QString errorMessage = ""; try { m_TrackingDeviceSource->StartTracking(); } catch (...) //todo: change to mitk::IGTException { errorMessage += "Error while starting the tracking device!"; emit StartTrackingFinished(false,errorMessage); return; } //remember the original colors of the tools m_OriginalColors = std::map(); for(int i=0; im_NavigationToolStorage->GetToolCount(); i++) { mitk::DataNode::Pointer currentToolNode = m_NavigationToolStorage->GetTool(i)->GetDataNode(); float c[3]; currentToolNode->GetColor(c); mitk::Color color; color.SetRed(c[0]); color.SetGreen(c[1]); color.SetBlue(c[2]); m_OriginalColors[currentToolNode] = color; } emit StartTrackingFinished(true,errorMessage); } void QmitkMITKIGTTrackingToolboxViewWorker::StopTracking() { //stop tracking try { m_TrackingDeviceSource->StopTracking(); } catch(mitk::Exception& e) { emit StopTrackingFinished(false, e.GetDescription()); } //restore the original colors of the tools for(int i=0; im_NavigationToolStorage->GetToolCount(); i++) { mitk::DataNode::Pointer currentToolNode = m_NavigationToolStorage->GetTool(i)->GetDataNode(); if (m_OriginalColors.find(currentToolNode) == m_OriginalColors.end()) {MITK_WARN << "Cannot restore original color of tool " << m_NavigationToolStorage->GetTool(i)->GetToolName();} else {currentToolNode->SetColor(m_OriginalColors[currentToolNode]);} } //emit signal emit StopTrackingFinished(true, ""); } void QmitkMITKIGTTrackingToolboxViewWorker::DisconnectDevice() { try { if (m_TrackingDeviceSource->IsTracking()) {m_TrackingDeviceSource->StopTracking();} m_TrackingDeviceSource->Disconnect(); m_TrackingDeviceSource->UnRegisterMicroservice(); m_NavigationToolStorage->UnLockStorage(); } catch(mitk::Exception& e) { emit DisconnectDeviceFinished(false, e.GetDescription()); } emit DisconnectDeviceFinished(true, ""); } diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h index cd302e7a12..e81ce25a4e 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h @@ -1,124 +1,122 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #define _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #include -#include #include #include #include "ui_QmitkMITKSurfaceMaterialEditorViewControls.h" /* #include #include #include #include #include #include #include "QtGui/QMenubarUpdatedEvent" */ #include "QmitkRenderWindow.h" #include "mitkCommon.h" #include "mitkDataStorage.h" #include "mitkDataNode.h" #include "mitkShaderProperty.h" #include "mitkSurface.h" #include "vtkRenderer.h" #include "vtkTextActor.h" /*! \brief QmitkMITKSurfaceMaterialEditorView \sa QmitkFunctionality \ingroup Functionalities */ class QmitkMITKSurfaceMaterialEditorView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkMITKSurfaceMaterialEditorView(); virtual ~QmitkMITKSurfaceMaterialEditorView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void OnSelectionChanged(std::vector nodes); protected slots: void SurfaceSelected(); protected: Ui::QmitkMITKSurfaceMaterialEditorViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; private: mitk::Surface::Pointer m_Surface; mitk::DataStorage::Pointer m_DataTree; mitk::DataNode::Pointer m_DataNode; mitk::DataNode::Pointer m_SelectedDataNode; std::list fixedProperties; std::list shaderProperties; unsigned long observerIndex; bool observerAllocated; mitk::ShaderProperty::Pointer observedProperty; void InitPreviewWindow(); int usedTimer; void timerEvent( QTimerEvent *e ); void RefreshPropertiesList(); void postRefresh(); void shaderEnumChange(const itk::Object *caller, const itk::EventObject &event); berry::IStructuredSelection::ConstPointer m_CurrentSelection; - berry::ISelectionListener::Pointer m_SelectionListener; }; #endif // _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h index 5ce6da2c3f..c43a4598e1 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.h @@ -1,184 +1,182 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkImageStatisticsView_H__INCLUDED #define QmitkImageStatisticsView_H__INCLUDED #include "ui_QmitkImageStatisticsViewControls.h" // Qmitk includes #include #include "QmitkStepperAdapter.h" #include "QmitkImageStatisticsCalculationThread.h" #include // mitk includes #include "mitkImageStatisticsCalculator.h" #include "mitkILifecycleAwarePart.h" #include "mitkPlanarLine.h" /*! \brief QmitkImageStatisticsView is a bundle that allows statistics calculation from images. Three modes are supported: 1. Statistics of one image, 2. Statistics of an image and a segmentation, 3. Statistics of an image and a Planar Figure. The statistics calculation is realized in a seperate thread to keep the gui accessable during calculation. \ingroup Plugins/org.mitk.gui.qt.measurementtoolbox */ class QmitkImageStatisticsView : public QmitkAbstractView, public mitk::ILifecycleAwarePart, public berry::IPartListener { Q_OBJECT private: /*! \ Convenient typedefs */ typedef mitk::DataStorage::SetOfObjects ConstVector; typedef ConstVector::ConstPointer ConstVectorPointer; typedef ConstVector::ConstIterator ConstVectorIterator; typedef std::map< mitk::Image *, mitk::ImageStatisticsCalculator::Pointer > ImageStatisticsMapType; typedef QList SelectedDataNodeVectorType; typedef itk::SimpleMemberCommand< QmitkImageStatisticsView > ITKCommandType; public: /*! \brief default constructor */ QmitkImageStatisticsView(QObject *parent=0, const char *name=0); /*! \brief default destructor */ virtual ~QmitkImageStatisticsView(); /*! \brief method for creating the widget containing the application controls, like sliders, buttons etc. */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief not implemented*/ //bool IsExclusiveFunctionality() const; /*! \brief Is called from the selection mechanism once the data manager selection has changed*/ void OnSelectionChanged( berry::IWorkbenchPart::Pointer part, const QList &nodes ); static const std::string VIEW_ID; static const int STAT_TABLE_BASE_HEIGHT; public slots: /** \brief Called when the statistics update is finished, sets the results to GUI.*/ void OnThreadedStatisticsCalculationEnds(); /** \brief Update bin size for histogram resolution. */ void OnHistogramBinSizeBoxValueChanged(); protected slots: /** \brief Saves the histogram to the clipboard */ void OnClipboardHistogramButtonClicked(); /** \brief Saves the statistics to the clipboard */ void OnClipboardStatisticsButtonClicked(); /** \brief Indicates if zeros should be excluded from statistics calculation */ void OnIgnoreZerosCheckboxClicked( ); /** \brief Checks if update is possible and calls StatisticsUpdate() possible */ void RequestStatisticsUpdate(); /** \brief Jump to coordinates stored in the double clicked cell */ void JumpToCoordinates(int row, int col); /** \brief Toogle GUI elements if histogram default bin size checkbox value changed. */ void OnDefaultBinSizeBoxChanged(); signals: /** \brief Method to set the data to the member and start the threaded statistics update */ void StatisticsUpdate(); protected: /** \brief Writes the calculated statistics to the GUI */ void FillStatisticsTableView( const std::vector &s, const mitk::Image *image ); /** \brief Removes statistics from the GUI */ void InvalidateStatisticsTableView(); /** \brief Recalculate statistics for currently selected image and mask and * update the GUI. */ void UpdateStatistics(); /** \brief Listener for progress events to update progress bar. */ void UpdateProgressBar(); /** \brief Removes any cached images which are no longer referenced elsewhere. */ void RemoveOrphanImages(); /** \brief Computes an Intensity Profile along line and updates the histogram widget with it. */ void ComputeIntensityProfile( mitk::PlanarLine* line ); /** \brief Removes all Observers to images, masks and planar figures and sets corresponding members to zero */ void ClearObservers(); void Activated(); void Deactivated(); void Visible(); void Hidden(); void SetFocus(); /** \brief Method called when itkModifiedEvent is called by selected data. */ void SelectedDataModified(); /** \brief Method called when the data manager selection changes */ void SelectionChanged(const QList &selectedNodes); /** \brief Method called to remove old selection when a new selection is present */ void ReinitData(); /** \brief writes the statistics to the gui*/ void WriteStatisticsToGUI(); void NodeRemoved(const mitk::DataNode *node); /** \brief Is called right before the view closes (before the destructor) */ virtual void PartClosed( berry::IWorkbenchPartReference::Pointer ); /** \brief Is called from the image navigator once the time step has changed */ void OnTimeChanged( const itk::EventObject& ); /** \brief Required for berry::IPartListener */ - virtual const char* GetClassName() const { return "QmitkImageStatisticsView"; } - /** \brief Required for berry::IPartListener */ virtual Events::Types GetPartEventTypes() const { return Events::CLOSED; } // member variables Ui::QmitkImageStatisticsViewControls *m_Controls; QmitkImageStatisticsCalculationThread* m_CalculationThread; QmitkStepperAdapter* m_TimeStepperAdapter; unsigned int m_CurrentTime; QString m_Clipboard; // Image and mask data mitk::Image* m_SelectedImage; mitk::Image* m_SelectedImageMask; mitk::PlanarFigure* m_SelectedPlanarFigure; // observer tags long m_ImageObserverTag; long m_ImageMaskObserverTag; long m_PlanarFigureObserverTag; long m_TimeObserverTag; SelectedDataNodeVectorType m_SelectedDataNodes; bool m_CurrentStatisticsValid; bool m_StatisticsUpdatePending; bool m_StatisticsIntegrationPending; bool m_DataNodeSelectionChanged; bool m_Visible; std::vector m_WorldMinList; std::vector m_WorldMaxList; }; #endif // QmitkImageStatisticsView_H__INCLUDED diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp index e03aea6d7c..1a8768f890 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.cpp @@ -1,690 +1,688 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkAnimationItemDelegate.h" #include "QmitkFFmpegWriter.h" #include "QmitkMovieMakerView.h" #include "QmitkOrbitAnimationItem.h" #include "QmitkOrbitAnimationWidget.h" #include "QmitkSliceAnimationItem.h" #include "QmitkSliceAnimationWidget.h" #include "QmitkTimeSliceAnimationWidget.h" #include "QmitkTimeSliceAnimationItem.h" #include #include #include #include #include #include #include #include static QmitkAnimationItem* CreateDefaultAnimation(const QString& widgetKey) { if (widgetKey == "Orbit") return new QmitkOrbitAnimationItem; if (widgetKey == "Slice") return new QmitkSliceAnimationItem; if (widgetKey == "Time") return new QmitkTimeSliceAnimationItem; return NULL; } -static QString GetFFmpegPath() +QString QmitkMovieMakerView::GetFFmpegPath() const { - berry::IPreferencesService::Pointer preferencesService = - berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID); - + berry::IPreferencesService* preferencesService = this->GetSite()->GetService(); berry::IPreferences::Pointer preferences = preferencesService->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); - return QString::fromStdString(preferences->Get("ffmpeg", "")); + return preferences->Get("ffmpeg", ""); } static unsigned char* ReadPixels(vtkRenderWindow* renderWindow, int x, int y, int width, int height) { if (renderWindow == NULL) return NULL; unsigned char* frame = new unsigned char[width * height * 3]; renderWindow->MakeCurrent(); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, frame); return frame; } const std::string QmitkMovieMakerView::VIEW_ID = "org.mitk.views.moviemaker"; QmitkMovieMakerView::QmitkMovieMakerView() : m_FFmpegWriter(NULL), m_Ui(new Ui::QmitkMovieMakerView), m_AnimationModel(NULL), m_AddAnimationMenu(NULL), m_RecordMenu(NULL), m_Timer(NULL), m_TotalDuration(0.0), m_NumFrames(0), m_CurrentFrame(0) { } QmitkMovieMakerView::~QmitkMovieMakerView() { } void QmitkMovieMakerView::CreateQtPartControl(QWidget* parent) { m_FFmpegWriter = new QmitkFFmpegWriter(parent); m_Ui->setupUi(parent); this->InitializeAnimationWidgets(); this->InitializeAnimationTreeViewWidgets(); this->InitializePlaybackAndRecordWidgets(); this->InitializeTimer(parent); m_Ui->animationWidgetGroupBox->setVisible(false); } void QmitkMovieMakerView::InitializeAnimationWidgets() { m_AnimationWidgets["Orbit"] = new QmitkOrbitAnimationWidget; m_AnimationWidgets["Slice"] = new QmitkSliceAnimationWidget; m_AnimationWidgets["Time"] = new QmitkTimeSliceAnimationWidget; Q_FOREACH(QWidget* widget, m_AnimationWidgets.values()) { if (widget != NULL) { widget->setVisible(false); m_Ui->animationWidgetGroupBoxLayout->addWidget(widget); } } this->ConnectAnimationWidgets(); } void QmitkMovieMakerView::InitializeAnimationTreeViewWidgets() { this->InitializeAnimationModel(); this->InitializeAddAnimationMenu(); this->ConnectAnimationTreeViewWidgets(); } void QmitkMovieMakerView::InitializePlaybackAndRecordWidgets() { this->InitializeRecordMenu(); this->ConnectPlaybackAndRecordWidgets(); } void QmitkMovieMakerView::InitializeAnimationModel() { m_AnimationModel = new QStandardItemModel(m_Ui->animationTreeView); m_AnimationModel->setHorizontalHeaderLabels(QStringList() << "Animation" << "Timeline"); m_Ui->animationTreeView->setModel(m_AnimationModel); m_Ui->animationTreeView->setItemDelegate(new QmitkAnimationItemDelegate(m_Ui->animationTreeView)); } void QmitkMovieMakerView::InitializeAddAnimationMenu() { m_AddAnimationMenu = new QMenu(m_Ui->addAnimationButton); Q_FOREACH(const QString& key, m_AnimationWidgets.keys()) { m_AddAnimationMenu->addAction(key); } } void QmitkMovieMakerView::InitializeRecordMenu() { typedef QPair PairOfStrings; m_RecordMenu = new QMenu(m_Ui->recordButton); QVector renderWindows; renderWindows.push_back(qMakePair(QString("Axial"), QString("stdmulti.widget1"))); renderWindows.push_back(qMakePair(QString("Sagittal"), QString("stdmulti.widget2"))); renderWindows.push_back(qMakePair(QString("Coronal"), QString("stdmulti.widget3"))); renderWindows.push_back(qMakePair(QString("3D"), QString("stdmulti.widget4"))); Q_FOREACH(const PairOfStrings& renderWindow, renderWindows) { QAction* action = new QAction(m_RecordMenu); action->setText(renderWindow.first); action->setData(renderWindow.second); m_RecordMenu->addAction(action); } } void QmitkMovieMakerView::InitializeTimer(QWidget* parent) { m_Timer = new QTimer(parent); this->OnFPSSpinBoxValueChanged(m_Ui->fpsSpinBox->value()); this->ConnectTimer(); } void QmitkMovieMakerView::ConnectAnimationTreeViewWidgets() { this->connect(m_AnimationModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(OnAnimationTreeViewRowsInserted(const QModelIndex&, int, int))); this->connect(m_AnimationModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(OnAnimationTreeViewRowsRemoved(const QModelIndex&, int, int))); this->connect(m_Ui->animationTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(OnAnimationTreeViewSelectionChanged(const QItemSelection&, const QItemSelection&))); this->connect(m_Ui->moveAnimationUpButton, SIGNAL(clicked()), this, SLOT(OnMoveAnimationUpButtonClicked())); this->connect(m_Ui->moveAnimationDownButton, SIGNAL(clicked()), this, SLOT(OnMoveAnimationDownButtonClicked())); this->connect(m_Ui->addAnimationButton, SIGNAL(clicked()), this, SLOT(OnAddAnimationButtonClicked())); this->connect(m_Ui->removeAnimationButton, SIGNAL(clicked()), this, SLOT(OnRemoveAnimationButtonClicked())); } void QmitkMovieMakerView::ConnectAnimationWidgets() { this->connect(m_Ui->startComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnStartComboBoxCurrentIndexChanged(int))); this->connect(m_Ui->durationSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnDurationSpinBoxValueChanged(double))); this->connect(m_Ui->delaySpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnDelaySpinBoxValueChanged(double))); } void QmitkMovieMakerView::ConnectPlaybackAndRecordWidgets() { this->connect(m_Ui->playButton, SIGNAL(toggled(bool)), this, SLOT(OnPlayButtonToggled(bool))); this->connect(m_Ui->stopButton, SIGNAL(clicked()), this, SLOT(OnStopButtonClicked())); this->connect(m_Ui->recordButton, SIGNAL(clicked()), this, SLOT(OnRecordButtonClicked())); this->connect(m_Ui->fpsSpinBox, SIGNAL(valueChanged(int)), this, SLOT(OnFPSSpinBoxValueChanged(int))); } void QmitkMovieMakerView::ConnectTimer() { this->connect(m_Timer, SIGNAL(timeout()), this, SLOT(OnTimerTimeout())); } void QmitkMovieMakerView::SetFocus() { m_Ui->addAnimationButton->setFocus(); } void QmitkMovieMakerView::OnMoveAnimationUpButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) { const int selectedRow = selection[0].top(); if (selectedRow > 0) m_AnimationModel->insertRow(selectedRow - 1, m_AnimationModel->takeRow(selectedRow)); } this->CalculateTotalDuration(); } void QmitkMovieMakerView::OnMoveAnimationDownButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) { const int rowCount = m_AnimationModel->rowCount(); const int selectedRow = selection[0].top(); if (selectedRow < rowCount - 1) m_AnimationModel->insertRow(selectedRow + 1, m_AnimationModel->takeRow(selectedRow)); } this->CalculateTotalDuration(); } void QmitkMovieMakerView::OnAddAnimationButtonClicked() { QAction* action = m_AddAnimationMenu->exec(QCursor::pos()); if (action != NULL) { const QString widgetKey = action->text(); m_AnimationModel->appendRow(QList() << new QStandardItem(widgetKey) << CreateDefaultAnimation(widgetKey)); m_Ui->playbackAndRecordingGroupBox->setEnabled(true); } } void QmitkMovieMakerView::OnPlayButtonToggled(bool checked) { if (checked) { m_Ui->playButton->setIcon(QIcon(":/org_mitk_icons/icons/tango/scalable/actions/media-playback-pause.svg")); m_Ui->playButton->repaint(); m_Timer->start(static_cast(1000.0 / m_Ui->fpsSpinBox->value())); } else { m_Timer->stop(); m_Ui->playButton->setIcon(QIcon(":/org_mitk_icons/icons/tango/scalable/actions/media-playback-start.svg")); m_Ui->playButton->repaint(); } } void QmitkMovieMakerView::OnStopButtonClicked() { m_Ui->playButton->setChecked(false); m_Ui->stopButton->setEnabled(false); m_CurrentFrame = 0; this->RenderCurrentFrame(); } void QmitkMovieMakerView::OnRecordButtonClicked() // TODO: Refactor { const QString ffmpegPath = GetFFmpegPath(); if (ffmpegPath.isEmpty()) { QMessageBox::information(NULL, "Movie Maker", "

Set path to FFmpeg1 or Libav2 (avconv) in preferences (Window -> Preferences... (Ctrl+P) -> External Programs) to be able to record your movies to video files.

" "

If you are using Linux, chances are good that either FFmpeg or Libav is included in the official package repositories.

" "

[1] Download FFmpeg from ffmpeg.org
" "[2] Download Libav from libav.org

"); return; } m_FFmpegWriter->SetFFmpegPath(GetFFmpegPath()); QAction* action = m_RecordMenu->exec(QCursor::pos()); if (action == NULL) return; vtkRenderWindow* renderWindow = mitk::BaseRenderer::GetRenderWindowByName(action->data().toString().toStdString()); if (renderWindow == NULL) return; const int border = 3; const int x = border; const int y = border; int width = renderWindow->GetSize()[0] - border * 2; int height = renderWindow->GetSize()[1] - border * 2; if (width & 1) --width; if (height & 1) --height; if (width < 16 || height < 16) return; m_FFmpegWriter->SetSize(width, height); m_FFmpegWriter->SetFramerate(m_Ui->fpsSpinBox->value()); QString saveFileName = QFileDialog::getSaveFileName(NULL, "Specify a filename", "", "Movie (*.mp4)"); if (saveFileName.isEmpty()) return; if(!saveFileName.endsWith(".mp4")) saveFileName += ".mp4"; m_FFmpegWriter->SetOutputPath(saveFileName); try { m_FFmpegWriter->Start(); for (m_CurrentFrame = 0; m_CurrentFrame < m_NumFrames; ++m_CurrentFrame) { this->RenderCurrentFrame(); renderWindow->MakeCurrent(); unsigned char* frame = ReadPixels(renderWindow, x, y, width, height); m_FFmpegWriter->WriteFrame(frame); delete[] frame; } m_FFmpegWriter->Stop(); m_CurrentFrame = 0; this->RenderCurrentFrame(); } catch (const mitk::Exception& exception) { m_CurrentFrame = 0; this->RenderCurrentFrame(); QMessageBox::critical(NULL, "Movie Maker", exception.GetDescription()); } } void QmitkMovieMakerView::OnRemoveAnimationButtonClicked() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (!selection.isEmpty()) m_AnimationModel->removeRow(selection[0].top()); } void QmitkMovieMakerView::OnAnimationTreeViewRowsInserted(const QModelIndex& parent, int start, int) { this->CalculateTotalDuration(); m_Ui->animationTreeView->selectionModel()->select( m_AnimationModel->index(start, 0, parent), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } void QmitkMovieMakerView::OnAnimationTreeViewRowsRemoved(const QModelIndex&, int, int) { this->CalculateTotalDuration(); this->UpdateWidgets(); } void QmitkMovieMakerView::OnAnimationTreeViewSelectionChanged(const QItemSelection&, const QItemSelection&) { this->UpdateWidgets(); } void QmitkMovieMakerView::OnStartComboBoxCurrentIndexChanged(int index) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != NULL) { item->SetStartWithPrevious(index); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnDurationSpinBoxValueChanged(double value) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != NULL) { item->SetDuration(value); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnDelaySpinBoxValueChanged(double value) { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != NULL) { item->SetDelay(value); this->RedrawTimeline(); this->CalculateTotalDuration(); } } void QmitkMovieMakerView::OnFPSSpinBoxValueChanged(int value) { this->CalculateTotalDuration(); m_Timer->setInterval(static_cast(1000.0 / value)); } void QmitkMovieMakerView::OnTimerTimeout() { this->RenderCurrentFrame(); m_CurrentFrame = std::min(m_NumFrames, m_CurrentFrame + 1); if (m_CurrentFrame >= m_NumFrames) { m_Ui->playButton->setChecked(false); m_CurrentFrame = 0; this->RenderCurrentFrame(); } m_Ui->stopButton->setEnabled(m_CurrentFrame != 0); } void QmitkMovieMakerView::RenderCurrentFrame() { typedef QPair AnimationInterpolationFactorPair; const double deltaT = m_TotalDuration / (m_NumFrames - 1); const QVector activeAnimations = this->GetActiveAnimations(m_CurrentFrame * deltaT); Q_FOREACH(const AnimationInterpolationFactorPair& animation, activeAnimations) { const QVector nextActiveAnimations = this->GetActiveAnimations((m_CurrentFrame + 1) * deltaT); bool lastFrameForAnimation = true; Q_FOREACH(const AnimationInterpolationFactorPair& nextAnimation, nextActiveAnimations) { if (nextAnimation.first == animation.first) { lastFrameForAnimation = false; break; } } animation.first->Animate(!lastFrameForAnimation ? animation.second : 1.0); } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkMovieMakerView::UpdateWidgets() { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); if (selection.isEmpty()) { m_Ui->moveAnimationUpButton->setEnabled(false); m_Ui->moveAnimationDownButton->setEnabled(false); m_Ui->removeAnimationButton->setEnabled(false); m_Ui->playbackAndRecordingGroupBox->setEnabled(false); this->HideCurrentAnimationWidget(); } else { const int rowCount = m_AnimationModel->rowCount(); const int selectedRow = selection[0].top(); m_Ui->moveAnimationUpButton->setEnabled(rowCount > 1 && selectedRow != 0); m_Ui->moveAnimationDownButton->setEnabled(rowCount > 1 && selectedRow < rowCount - 1); m_Ui->removeAnimationButton->setEnabled(true); m_Ui->playbackAndRecordingGroupBox->setEnabled(true); this->ShowAnimationWidget(dynamic_cast(m_AnimationModel->item(selectedRow, 1))); } this->UpdateAnimationWidgets(); } void QmitkMovieMakerView::UpdateAnimationWidgets() { QmitkAnimationItem* item = this->GetSelectedAnimationItem(); if (item != NULL) { m_Ui->startComboBox->setCurrentIndex(item->GetStartWithPrevious()); m_Ui->durationSpinBox->setValue(item->GetDuration()); m_Ui->delaySpinBox->setValue(item->GetDelay()); m_Ui->animationGroupBox->setEnabled(true); } else { m_Ui->animationGroupBox->setEnabled(false); } } void QmitkMovieMakerView::HideCurrentAnimationWidget() { if (m_Ui->animationWidgetGroupBox->isVisible()) { m_Ui->animationWidgetGroupBox->setVisible(false); int numWidgets = m_Ui->animationWidgetGroupBoxLayout->count(); for (int i = 0; i < numWidgets; ++i) m_Ui->animationWidgetGroupBoxLayout->itemAt(i)->widget()->setVisible(false); } } void QmitkMovieMakerView::ShowAnimationWidget(QmitkAnimationItem* animationItem) { this->HideCurrentAnimationWidget(); if (animationItem == NULL) return; const QString widgetKey = animationItem->GetWidgetKey(); QmitkAnimationWidget* animationWidget = NULL; if (m_AnimationWidgets.contains(widgetKey)) { animationWidget = m_AnimationWidgets[widgetKey]; if (animationWidget != NULL) { m_Ui->animationWidgetGroupBox->setTitle(widgetKey); animationWidget->SetAnimationItem(animationItem); animationWidget->setVisible(true); } } m_Ui->animationWidgetGroupBox->setVisible(animationWidget != NULL); } void QmitkMovieMakerView::RedrawTimeline() { if (m_AnimationModel->rowCount() > 1) { m_Ui->animationTreeView->dataChanged( m_AnimationModel->index(0, 1), m_AnimationModel->index(m_AnimationModel->rowCount() - 1, 1)); } } QmitkAnimationItem* QmitkMovieMakerView::GetSelectedAnimationItem() const { const QItemSelection selection = m_Ui->animationTreeView->selectionModel()->selection(); return !selection.isEmpty() ? dynamic_cast(m_AnimationModel->item(selection[0].top(), 1)) : NULL; } void QmitkMovieMakerView::CalculateTotalDuration() { const int rowCount = m_AnimationModel->rowCount(); double totalDuration = 0.0; double previousStart = 0.0; for (int i = 0; i < rowCount; ++i) { QmitkAnimationItem* item = dynamic_cast(m_AnimationModel->item(i, 1)); if (item == NULL) continue; if (item->GetStartWithPrevious()) { totalDuration = std::max(totalDuration, previousStart + item->GetDelay() + item->GetDuration()); } else { previousStart = totalDuration; totalDuration += item->GetDelay() + item->GetDuration(); } } m_TotalDuration = totalDuration; // TODO totalDuration == 0 m_NumFrames = static_cast(totalDuration * m_Ui->fpsSpinBox->value()); // TODO numFrames < 2 } QVector > QmitkMovieMakerView::GetActiveAnimations(double t) const { const int rowCount = m_AnimationModel->rowCount(); QVector > activeAnimations; double totalDuration = 0.0; double previousStart = 0.0; for (int i = 0; i < rowCount; ++i) { QmitkAnimationItem* item = dynamic_cast(m_AnimationModel->item(i, 1)); if (item == NULL) continue; if (item->GetDuration() > 0.0) { double start = item->GetStartWithPrevious() ? previousStart + item->GetDelay() : totalDuration + item->GetDelay(); if (start <= t && t <= start + item->GetDuration()) activeAnimations.push_back(qMakePair(item, (t - start) / item->GetDuration())); } if (item->GetStartWithPrevious()) { totalDuration = std::max(totalDuration, previousStart + item->GetDelay() + item->GetDuration()); } else { previousStart = totalDuration; totalDuration += item->GetDelay() + item->GetDuration(); } } return activeAnimations; } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.h b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.h index f686ba79b9..f1949b12dc 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.h +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerView.h @@ -1,98 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkMovieMakerView_h #define QmitkMovieMakerView_h #include class QmitkAnimationItem; class QmitkAnimationWidget; class QmitkFFmpegWriter; class QMenu; class QStandardItemModel; class QTimer; namespace Ui { class QmitkMovieMakerView; } class QmitkMovieMakerView : public QmitkAbstractView { Q_OBJECT public: static const std::string VIEW_ID; QmitkMovieMakerView(); ~QmitkMovieMakerView(); void CreateQtPartControl(QWidget* parent); void SetFocus(); private slots: void OnMoveAnimationUpButtonClicked(); void OnMoveAnimationDownButtonClicked(); void OnAddAnimationButtonClicked(); void OnRemoveAnimationButtonClicked(); void OnAnimationTreeViewRowsInserted(const QModelIndex& parent, int start, int end); void OnAnimationTreeViewRowsRemoved(const QModelIndex& parent, int start, int end); void OnAnimationTreeViewSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void OnStartComboBoxCurrentIndexChanged(int index); void OnDurationSpinBoxValueChanged(double value); void OnDelaySpinBoxValueChanged(double value); void OnPlayButtonToggled(bool checked); void OnStopButtonClicked(); void OnRecordButtonClicked(); void OnFPSSpinBoxValueChanged(int value); void OnTimerTimeout(); private: void InitializeAnimationWidgets(); void InitializeAnimationTreeViewWidgets(); void InitializeAnimationModel(); void InitializeAddAnimationMenu(); void InitializePlaybackAndRecordWidgets(); void InitializeRecordMenu(); void InitializeTimer(QWidget* parent); void ConnectAnimationTreeViewWidgets(); void ConnectAnimationWidgets(); void ConnectPlaybackAndRecordWidgets(); void ConnectTimer(); void RenderCurrentFrame(); void UpdateWidgets(); void UpdateAnimationWidgets(); void HideCurrentAnimationWidget(); void ShowAnimationWidget(QmitkAnimationItem* animationItem); void RedrawTimeline(); void CalculateTotalDuration(); QmitkAnimationItem* GetSelectedAnimationItem() const; QVector > GetActiveAnimations(double t) const; + QString GetFFmpegPath() const; + QmitkFFmpegWriter* m_FFmpegWriter; Ui::QmitkMovieMakerView* m_Ui; QStandardItemModel* m_AnimationModel; QMap m_AnimationWidgets; QMenu* m_AddAnimationMenu; QMenu* m_RecordMenu; QTimer* m_Timer; double m_TotalDuration; int m_NumFrames; int m_CurrentFrame; }; #endif diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.cpp index 67a6181d93..5c1240d35e 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.cpp @@ -1,82 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPropertiesPreferencePage.h" #include +#include -const std::string QmitkPropertiesPreferencePage::FILTER_PROPERTIES = "filter properties"; -const std::string QmitkPropertiesPreferencePage::SHOW_ALIASES = "show aliases"; -const std::string QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS = "show descriptions"; -const std::string QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION = "show aliases in description"; -const std::string QmitkPropertiesPreferencePage::DEVELOPER_MODE = "enable developer mode"; +const QString QmitkPropertiesPreferencePage::FILTER_PROPERTIES = "filter properties"; +const QString QmitkPropertiesPreferencePage::SHOW_ALIASES = "show aliases"; +const QString QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS = "show descriptions"; +const QString QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION = "show aliases in description"; +const QString QmitkPropertiesPreferencePage::DEVELOPER_MODE = "enable developer mode"; QmitkPropertiesPreferencePage::QmitkPropertiesPreferencePage() : m_Control(NULL), - m_Preferences(berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID)->GetSystemPreferences()->Node("/org.mitk.views.properties")) + m_Preferences(berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.properties")) { } QmitkPropertiesPreferencePage::~QmitkPropertiesPreferencePage() { } void QmitkPropertiesPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_Controls.setupUi(m_Control); connect(m_Controls.showDescriptionsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnShowDescriptionsStateChanged(int))); this->Update(); } QWidget* QmitkPropertiesPreferencePage::GetQtControl() const { return m_Control; } void QmitkPropertiesPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkPropertiesPreferencePage::OnShowDescriptionsStateChanged(int state) { m_Controls.showAliasesInDescriptionCheckBox->setEnabled(state != Qt::Unchecked); } bool QmitkPropertiesPreferencePage::PerformOk() { m_Preferences->PutBool(FILTER_PROPERTIES, m_Controls.filterPropertiesCheckBox->isChecked()); m_Preferences->PutBool(SHOW_ALIASES, m_Controls.showAliasesCheckBox->isChecked()); m_Preferences->PutBool(SHOW_DESCRIPTIONS, m_Controls.showDescriptionsCheckBox->isChecked()); m_Preferences->PutBool(SHOW_ALIASES_IN_DESCRIPTION, m_Controls.showAliasesInDescriptionCheckBox->isChecked()); m_Preferences->PutBool(DEVELOPER_MODE, m_Controls.enableDeveloperModeCheckBox->isChecked()); return true; } void QmitkPropertiesPreferencePage::PerformCancel() { } void QmitkPropertiesPreferencePage::Update() { m_Controls.filterPropertiesCheckBox->setChecked(m_Preferences->GetBool(FILTER_PROPERTIES, true)); m_Controls.showAliasesCheckBox->setChecked(m_Preferences->GetBool(SHOW_ALIASES, true)); m_Controls.showDescriptionsCheckBox->setChecked(m_Preferences->GetBool(SHOW_DESCRIPTIONS, true)); m_Controls.showAliasesInDescriptionCheckBox->setChecked(m_Preferences->GetBool(SHOW_ALIASES_IN_DESCRIPTION, true)); m_Controls.enableDeveloperModeCheckBox->setChecked(m_Preferences->GetBool(DEVELOPER_MODE, false)); } diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.h b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.h index ac9e77823e..842ec748f5 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertiesPreferencePage.h @@ -1,54 +1,54 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkPropertiesPreferencePage_h #define QmitkPropertiesPreferencePage_h #include #include class QmitkPropertiesPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: - static const std::string FILTER_PROPERTIES; - static const std::string SHOW_ALIASES; - static const std::string SHOW_DESCRIPTIONS; - static const std::string SHOW_ALIASES_IN_DESCRIPTION; - static const std::string DEVELOPER_MODE; + static const QString FILTER_PROPERTIES; + static const QString SHOW_ALIASES; + static const QString SHOW_DESCRIPTIONS; + static const QString SHOW_ALIASES_IN_DESCRIPTION; + static const QString DEVELOPER_MODE; QmitkPropertiesPreferencePage(); ~QmitkPropertiesPreferencePage(); void CreateQtControl(QWidget* parent); QWidget* GetQtControl() const; void Init(berry::IWorkbench::Pointer workbench); bool PerformOk(); void PerformCancel(); void Update(); private slots: void OnShowDescriptionsStateChanged(int state); private: QWidget* m_Control; Ui::QmitkPropertiesPreferencePage m_Controls; berry::IPreferences::Pointer m_Preferences; }; #endif diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp index be0d59a9be..895badd6b5 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp @@ -1,409 +1,409 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkGetPropertyService.h" #include "QmitkAddNewPropertyDialog.h" #include "QmitkPropertiesPreferencePage.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" #include #include #include #include #include const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() : m_Parent(NULL), m_PropertyNameChangedTag(0), m_PropertyAliases(NULL), m_PropertyDescriptions(NULL), m_ShowAliasesInDescription(true), m_DeveloperMode(false), m_ProxyModel(NULL), m_Model(NULL), m_Delegate(NULL), m_Renderer(NULL) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) { m_Parent = parent; m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != NULL) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); m_Controls.description->hide(); m_Controls.propertyListLabel->hide(); m_Controls.propertyListComboBox->hide(); m_Controls.newButton->hide(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); connect(m_Controls.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterTextChanged(const QString&))); connect(m_Controls.propertyListComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int))); connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty())); connect(m_Controls.treeView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnCurrentRowChanged(const QModelIndex&, const QModelIndex&))); connect(m_Model, SIGNAL(modelReset()), this, SLOT(OnModelReset())); } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (m_PropertyDescriptions != NULL && current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; if (m_PropertyAliases != NULL) { std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector aliases; if (!isTrueName && m_PropertyAliases != NULL) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } if (!description.isEmpty() || !aliases.empty()) { QString customizedDescription; if (m_ShowAliasesInDescription && !aliases.empty()) { customizedDescription = "

" + name + "

"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "
" : "
"; customizedDescription += QString::fromStdString(aliases[i]) + "
"; } } else { customizedDescription = "

" + name + "

"; } if (!description.isEmpty()) customizedDescription += description; m_Controls.description->setText(customizedDescription); m_Controls.description->show(); return; } } } m_Controls.description->hide(); } void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { m_ProxyModel->setFilterWildcard(filter); if (filter.isEmpty()) m_Controls.treeView->collapseAll(); else m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::OnModelReset() { m_Controls.description->hide(); } void QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences) { bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true); bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true); bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true); bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false); bool updateAliases = showAliases != (m_PropertyAliases != NULL); bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != NULL); bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription; bool updateDeveloperMode = developerMode != m_DeveloperMode; if (updateAliases) m_PropertyAliases = showAliases ? mitk::GetPropertyService() : NULL; if (updateDescriptions) m_PropertyDescriptions = showDescriptions ? mitk::GetPropertyService() : NULL; if (updateAliasesInDescription) m_ShowAliasesInDescription = showAliasesInDescription; if (updateDescriptions || updateAliasesInDescription) { QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows(); if (!selection.isEmpty()) this->OnCurrentRowChanged(selection[0], selection[0]); } if (updateDeveloperMode) { m_DeveloperMode = developerMode; if (!developerMode) m_Controls.propertyListComboBox->setCurrentIndex(0); m_Controls.propertyListLabel->setVisible(developerMode); m_Controls.propertyListComboBox->setVisible(developerMode); m_Controls.newButton->setVisible(developerMode); } m_Model->OnPreferencesChanged(preferences); } void QmitkPropertyTreeView::OnPropertyNameChanged(const itk::EventObject&) { mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (propertyList != NULL) { mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); if (nameProperty != NULL) { - std::ostringstream partName; - partName << "Properties (" << nameProperty->GetValueAsString() << ')'; - this->SetPartName(partName.str()); + QString partName = "Properties ("; + partName.append(QString::fromStdString(nameProperty->GetValueAsString())).append(')'); + this->SetPartName(partName); } } } void QmitkPropertyTreeView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes) { mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (propertyList != NULL) { mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); if (nameProperty != NULL) nameProperty->RemoveObserver(m_PropertyNameChangedTag); m_PropertyNameChangedTag = 0; } if (nodes.empty() || nodes.front().IsNull()) { m_SelectedNode = NULL; this->SetPartName("Properties"); m_Model->SetPropertyList(NULL); m_Delegate->SetPropertyList(NULL); m_Controls.newButton->setEnabled(false); } else { m_SelectedNode = nodes.front(); QString selectionClassName = m_SelectedNode->GetData() != NULL ? m_SelectedNode->GetData()->GetNameOfClass() : ""; m_SelectionClassName = selectionClassName.toStdString(); mitk::PropertyList::Pointer propertyList; if (m_Renderer == NULL && m_Controls.propertyListComboBox->currentText() == "Base data") { propertyList = m_SelectedNode->GetData() != NULL ? m_SelectedNode->GetData()->GetPropertyList() : NULL; } else { propertyList = m_SelectedNode->GetPropertyList(m_Renderer); } m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); OnPropertyNameChanged(itk::ModifiedEvent()); mitk::BaseProperty* nameProperty = m_SelectedNode->GetProperty("name"); if (nameProperty != NULL) { itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkPropertyTreeView::OnPropertyNameChanged); m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command); } m_Controls.newButton->setEnabled(true); } if (!m_ProxyModel->filterRegExp().isEmpty()) m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::SetFocus() { m_Controls.filterLineEdit->setFocus(); } void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_Controls.propertyListComboBox->count() == 2) { QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); } } } void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) { if (m_Controls.propertyListComboBox->count() > 2) { m_Controls.propertyListComboBox->clear(); m_Controls.propertyListComboBox->addItem("Data node: common"); m_Controls.propertyListComboBox->addItem("Base data"); } } void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = renderer != "common" && renderer != "Base data" ? this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer)->GetRenderer() : NULL; QList nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; berry::IWorkbenchPart::Pointer workbenchPart; this->OnSelectionChanged(workbenchPart, nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { QmitkAddNewPropertyDialog dialog(m_SelectedNode, m_Renderer, m_Parent); if (dialog.exec() == QDialog::Accepted) this->m_Model->Update(); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp index 991b99dfeb..9a94ac2f6d 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.cpp @@ -1,627 +1,625 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDeformableRegistrationView.h" #include "ui_QmitkDeformableRegistrationViewControls.h" #include "QmitkStdMultiWidget.h" #include "qinputdialog.h" #include "qmessagebox.h" #include "qcursor.h" #include "qapplication.h" #include "qradiobutton.h" #include "qslider.h" #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateNot.h" #include "mitkVectorImageMapper2D.h" #include #include "itkWarpImageFilter.h" #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkDeformableRegistrationView::VIEW_ID = "org.mitk.views.deformableregistration"; using namespace berry; struct SelListenerDeformableRegistration : ISelectionListener { berryObjectMacro(SelListenerDeformableRegistration); SelListenerDeformableRegistration(QmitkDeformableRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_SwitchImages->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.m_OpacityLabel->setEnabled(false); m_View->m_Controls.m_OpacitySlider->setEnabled(false); m_View->m_Controls.label->setEnabled(false); m_View->m_Controls.label_2->setEnabled(false); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "DeformableRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_SwitchImages->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.m_OpacityLabel->setEnabled(true); m_View->m_Controls.m_OpacitySlider->setEnabled(true); m_View->m_Controls.label->setEnabled(true); m_View->m_Controls.label_2->setEnabled(true); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, const ISelection::ConstPointer& selection) { // check, if selection comes from datamanager if (part) { - QString partname(part->GetPartName().c_str()); + QString partname = part->GetPartName(); if(partname.compare("Data Manager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkDeformableRegistrationView* m_View; }; QmitkDeformableRegistrationView::QmitkDeformableRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality() , m_MultiWidget(NULL), m_MovingNode(NULL), m_FixedNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Deactivated(false) { this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkDeformableRegistrationView::DataNodeHasBeenRemoved )); } QmitkDeformableRegistrationView::~QmitkDeformableRegistrationView() { - if (m_SelListener.IsNotNull()) + if (m_SelListener) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + if(s) s->RemovePostSelectionListener(m_SelListener.data()); } } void QmitkDeformableRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Parent->setEnabled(false); this->CreateConnections(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_DeformableTransform->hide(); if (m_Controls.m_DeformableTransform->currentIndex() == 0) { m_Controls.m_QmitkDemonsRegistrationViewControls->show(); m_Controls.m_QmitkBSplineRegistrationViewControls->hide(); } else { m_Controls.m_QmitkDemonsRegistrationViewControls->hide(); m_Controls.m_QmitkBSplineRegistrationViewControls->show(); } this->CheckCalculateEnabled(); mitk::TNodePredicateDataType::Pointer isMitkImage = mitk::TNodePredicateDataType::New(); m_Controls.comboBox->SetDataStorage(this->GetDataStorage()); m_Controls.comboBox->SetPredicate(isMitkImage); m_Controls.comboBox_2->SetDataStorage(this->GetDataStorage()); m_Controls.comboBox_2->SetPredicate(isMitkImage); } void QmitkDeformableRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_DeformableTransform->hide(); m_Controls.m_CalculateTransformation->setEnabled(false); } } void QmitkDeformableRegistrationView::ApplyDeformationField() { if ( m_Controls.comboBox->GetSelectedNode().IsNull() || m_Controls.comboBox_2->GetSelectedNode().IsNull() ) return; mitk::Image* mitkDeformationField = dynamic_cast(m_Controls.comboBox->GetSelectedNode()->GetData()); mitk::Image* mimage = dynamic_cast(m_Controls.comboBox_2->GetSelectedNode()->GetData()); typedef itk::Image FloatImageType; FloatImageType::Pointer itkMovingImage = FloatImageType::New(); DeformationFieldType::Pointer itkDeformationField = DeformationFieldType::New(); mitk::CastToItkImage(mimage, itkMovingImage); mitk::CastToItkImage(mitkDeformationField, itkDeformationField); typedef itk::WarpImageFilter< FloatImageType, FloatImageType, DeformationFieldType > WarperType; typedef itk::LinearInterpolateImageFunction< FloatImageType, double > InterpolatorType; WarperType::Pointer warper = WarperType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); warper->SetInput( itkMovingImage ); warper->SetInterpolator( interpolator ); warper->SetOutputSpacing( itkDeformationField->GetSpacing() ); warper->SetOutputOrigin( itkDeformationField->GetOrigin() ); warper->SetOutputDirection (itkDeformationField->GetDirection() ); warper->SetDisplacementField( itkDeformationField ); warper->Update(); FloatImageType::Pointer outputImage = warper->GetOutput(); mitk::Image::Pointer result = mitk::Image::New(); mitk::CastToMitkImage(outputImage, result); // Create new DataNode mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetData( result ); newNode->SetProperty( "name", mitk::StringProperty::New("warped image") ); // add the new datatree node to the datatree this->GetDefaultDataStorage()->Add(newNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); } void QmitkDeformableRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; } void QmitkDeformableRegistrationView::CreateConnections() { connect(m_Controls.m_ShowRedGreenValues, SIGNAL(toggled(bool)), this, SLOT(ShowRedGreen(bool))); connect(m_Controls.m_DeformableTransform, SIGNAL(currentChanged(int)), this, SLOT(TabChanged(int))); connect(m_Controls.m_OpacitySlider, SIGNAL(sliderMoved(int)), this, SLOT(OpacityUpdate(int))); connect(m_Controls.m_CalculateTransformation, SIGNAL(clicked()), this, SLOT(Calculate())); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect(this,SIGNAL(calculateBSplineRegistration()),m_Controls.m_QmitkBSplineRegistrationViewControls,SLOT(CalculateTransformation())); connect( m_Controls.m_WarpImageButton, SIGNAL(clicked()), this, SLOT(ApplyDeformationField()) ); } void QmitkDeformableRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); - if (m_SelListener.IsNull()) + if (m_SelListener.isNull()) { - m_SelListener = berry::ISelectionListener::Pointer(new SelListenerDeformableRegistration(this)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + m_SelListener.reset(new SelListenerDeformableRegistration(this)); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); + static_cast(m_SelListener.data())->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); } void QmitkDeformableRegistrationView::Visible() { /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerDeformableRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener("org.mitk.views.datamanager", m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked());*/ } void QmitkDeformableRegistrationView::Deactivated() { m_Deactivated = true; this->SetImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } m_FixedNode = NULL; m_MovingNode = NULL; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + s->RemovePostSelectionListener(m_SelListener.data()); + m_SelListener.reset(); } void QmitkDeformableRegistrationView::Hidden() { /* m_Deactivated = true; this->SetImageColor(false); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } m_FixedNode = NULL; m_MovingNode = NULL; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL;*/ //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated(); } void QmitkDeformableRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if (fixedImage.IsNotNull()) { if (m_FixedNode != fixedImage) { // remove changes on previous selected node if (m_FixedNode.IsNotNull()) { this->SetImageColor(false); m_FixedNode->SetOpacity(1.0); m_FixedNode->SetVisibility(false); m_FixedNode->SetProperty("selectedFixedImage", mitk::BoolProperty::New(false)); } // get selected node m_FixedNode = fixedImage; m_FixedNode->SetOpacity(0.5); m_Controls.TextLabelFixed->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.TextLabelFixed->show(); m_Controls.m_SwitchImages->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_FixedNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_FixedNode = fixedImage; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); } this->CheckCalculateEnabled(); } void QmitkDeformableRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if (movingImage.IsNotNull()) { if (m_MovingNode != movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->SetImageColor(false); } m_MovingNode = movingImage; m_Controls.TextLabelMoving->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); m_MovingNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_MovingNode = NULL; m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); } this->CheckCalculateEnabled(); } bool QmitkDeformableRegistrationView::CheckCalculate() { if(m_MovingNode==m_FixedNode) return false; return true; } void QmitkDeformableRegistrationView::ShowRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->SetImageColor(m_ShowRedGreen); } void QmitkDeformableRegistrationView::SetImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableRegistrationView::OpacityUpdate(float opacity) { m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkDeformableRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkDeformableRegistrationView::CheckCalculateEnabled() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { m_Controls.m_CalculateTransformation->setEnabled(true); } else { m_Controls.m_CalculateTransformation->setEnabled(false); } } void QmitkDeformableRegistrationView::Calculate() { if (m_Controls.m_DeformableTransform->tabText(m_Controls.m_DeformableTransform->currentIndex()) == "Demons") { m_Controls.m_QmitkDemonsRegistrationViewControls->SetFixedNode(m_FixedNode); m_Controls.m_QmitkDemonsRegistrationViewControls->SetMovingNode(m_MovingNode); try { m_Controls.m_QmitkDemonsRegistrationViewControls->CalculateTransformation(); } catch (itk::ExceptionObject& excpt) { QMessageBox::information( NULL, "Registration exception", excpt.GetDescription(), QMessageBox::Ok ); return; } mitk::Image::Pointer resultImage = m_Controls.m_QmitkDemonsRegistrationViewControls->GetResultImage(); mitk::Image::Pointer resultDeformationField = m_Controls.m_QmitkDemonsRegistrationViewControls->GetResultDeformationfield(); if (resultImage.IsNotNull()) { mitk::DataNode::Pointer resultImageNode = mitk::DataNode::New(); resultImageNode->SetData(resultImage); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( resultImage ); levWinProp->SetLevelWindow(levelWindow); resultImageNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); resultImageNode->SetStringProperty("name", "DeformableRegistrationResultImage"); this->GetDataStorage()->Add(resultImageNode, m_MovingNode); } if (resultDeformationField.IsNotNull()) { mitk::DataNode::Pointer resultDeformationFieldNode = mitk::DataNode::New(); resultDeformationFieldNode->SetData(resultDeformationField); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( resultDeformationField ); levWinProp->SetLevelWindow(levelWindow); resultDeformationFieldNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); resultDeformationFieldNode->SetStringProperty("name", "DeformableRegistrationResultDeformationField"); mitk::VectorImageMapper2D::Pointer mapper = mitk::VectorImageMapper2D::New(); resultDeformationFieldNode->SetMapper(1, mapper); resultDeformationFieldNode->SetVisibility(false); this->GetDataStorage()->Add(resultDeformationFieldNode, m_MovingNode); } } else if (m_Controls.m_DeformableTransform->tabText(m_Controls.m_DeformableTransform->currentIndex()) == "B-Spline") { m_Controls.m_QmitkBSplineRegistrationViewControls->SetFixedNode(m_FixedNode); m_Controls.m_QmitkBSplineRegistrationViewControls->SetMovingNode(m_MovingNode); emit calculateBSplineRegistration(); } } void QmitkDeformableRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkDeformableRegistrationView::TabChanged(int index) { if (index == 0) { m_Controls.m_QmitkDemonsRegistrationViewControls->show(); m_Controls.m_QmitkBSplineRegistrationViewControls->hide(); } else { m_Controls.m_QmitkDemonsRegistrationViewControls->hide(); m_Controls.m_QmitkBSplineRegistrationViewControls->show(); } } void QmitkDeformableRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h index 0bb7970543..c88a4f0cf9 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkDeformableRegistrationView.h @@ -1,214 +1,214 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKDEFORMABLEREGISTRATION_H #define QMITKDEFORMABLEREGISTRATION_H #include "QmitkFunctionality.h" #include "ui_QmitkDeformableRegistrationViewControls.h" #include #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include #include "itkImageFileReader.h" /*! \brief The DeformableRegistration functionality is used to perform deformable registration. This functionality allows you to register two 2D as well as two 3D images in a non rigid manner. Register means to align two images, so that they become as similar as possible. Therefore you can select from different deformable registration methods. Registration results will directly be applied to the Moving Image. The result is shown in the multi-widget. For more informations see: \ref QmitkDeformableRegistrationUserManual \sa QmitkFunctionality \ingroup Functionalities \ingroup DeformableRegistration */ class REGISTRATION_EXPORT QmitkDeformableRegistrationView : public QmitkFunctionality { friend struct SelListenerDeformableRegistration; Q_OBJECT public: static const std::string VIEW_ID; typedef itk::Vector< float, 3 > VectorType; typedef itk::Image< VectorType, 3 > DeformationFieldType; typedef itk::ImageFileReader< DeformationFieldType > ImageReaderType; /*! \brief default constructor */ QmitkDeformableRegistrationView(QObject *parent=0, const char *name=0); /*! \brief default destructor */ virtual ~QmitkDeformableRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief Method which is called when this functionality is selected in MITK */ virtual void Activated(); /*! \brief Method which is called whenever the functionality is deselected in MITK */ virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); void DataNodeHasBeenRemoved(const mitk::DataNode* node); signals: /*! \brief Signal that informs about that the fixed image should be reinitialized in the multi-widget. */ void reinitFixed(const mitk::Geometry3D *); /*! \brief Signal that informs about that the moving image should be reinitialized in the multi-widget. */ void reinitMoving(const mitk::Geometry3D *); /*! \brief Signal that informs about that the BSpline registration should be performed. */ void calculateBSplineRegistration(); protected slots: /*! * sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! * sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! * checks if registration is possible */ bool CheckCalculate(); /*! * stores whether the image will be shown in grayvalues or in red for fixed image and green for moving image * @param show if true, then images will be shown in red and green */ void ShowRedGreen(bool show); /*! * set the selected opacity for moving image * @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! * sets the images to grayvalues or fixed image to red and moving image to green * @param redGreen if true, then images will be shown in red and green */ void SetImageColor(bool redGreen); /*! \brief Checks whether the registration can be performed. */ void CheckCalculateEnabled(); /*! \brief Performs the registration. */ void Calculate(); /*! * Prints the values of the deformationfield */ void ApplyDeformationField(); void SetImagesVisible(berry::ISelection::ConstPointer selection); void TabChanged(int index); void SwitchImages(); protected: - berry::ISelectionListener::Pointer m_SelListener; + QScopedPointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for Deformable registration */ Ui::QmitkDeformableRegistrationViewControls m_Controls; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_FixedNode; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; mitk::Color m_FixedColor; mitk::Color m_MovingColor; bool m_Deactivated; }; #endif //QMITKDEFORMABLEREGISTRATION_H diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp index 1e5b35cfac..c08648b13a 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.cpp @@ -1,1329 +1,1327 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPointBasedRegistrationView.h" #include "ui_QmitkPointBasedRegistrationViewControls.h" #include "QmitkPointListWidget.h" #include #include #include #include "vtkPolyData.h" #include #include #include "qradiobutton.h" #include "qapplication.h" #include #include #include #include #include "qmessagebox.h" #include "mitkLandmarkWarping.h" #include #include #include "mitkOperationEvent.h" #include "mitkUndoController.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateNot.h" #include #include #include #include "mitkDataNodeObject.h" #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkPointBasedRegistrationView::VIEW_ID = "org.mitk.views.pointbasedregistration"; using namespace berry; struct SelListenerPointBasedRegistration : ISelectionListener { berryObjectMacro(SelListenerPointBasedRegistration); SelListenerPointBasedRegistration(QmitkPointBasedRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // if(!m_View->IsVisible()) // return; // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.line2->hide(); m_View->m_Controls.m_FixedPointListWidget->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.line1->hide(); m_View->m_Controls.m_MovingPointListWidget->hide(); m_View->m_Controls.m_OpacityLabel->hide(); m_View->m_Controls.m_OpacitySlider->hide(); m_View->m_Controls.label->hide(); m_View->m_Controls.label_2->hide(); m_View->m_Controls.m_SwitchImages->hide(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::TNodePredicateDataType::Pointer isBaseData(mitk::TNodePredicateDataType::New()); mitk::TNodePredicateDataType::Pointer isPointSet(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notPointSet = mitk::NodePredicateNot::New(isPointSet); mitk::TNodePredicateDataType::Pointer isPlaneGeometryData(mitk::TNodePredicateDataType::New()); mitk::NodePredicateNot::Pointer notPlaneGeometryData = mitk::NodePredicateNot::New(isPlaneGeometryData); mitk::NodePredicateAnd::Pointer notPointSetAndNotPlaneGeometryData = mitk::NodePredicateAnd::New( notPointSet, notPlaneGeometryData ); mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New( isBaseData, notPointSetAndNotPlaneGeometryData ); mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = m_View->GetDataStorage()->GetSubset(predicate); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if(nodeIt->Value().GetPointer() == node.GetPointer()) { // was - compare() // use contain to allow other Image types to be selected, i.e. a diffusion image if (QString( node->GetData()->GetNameOfClass() ).contains("Image") ) { // verify that the node selected by name is really an image or derived class mitk::Image* _image = dynamic_cast(node->GetData()); if (_image != NULL) { if( _image->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "PointBasedRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { // method deleted for more information see bug-18492 // m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.line2->show(); m_View->m_Controls.m_FixedPointListWidget->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.line1->show(); m_View->m_Controls.m_MovingPointListWidget->show(); m_View->m_Controls.m_OpacityLabel->show(); m_View->m_Controls.m_OpacitySlider->show(); m_View->m_Controls.label->show(); m_View->m_Controls.label_2->show(); m_View->m_Controls.m_SwitchImages->show(); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& selection) override { // check, if selection comes from datamanager if (part) { - QString partname(part->GetPartName().c_str()); - if(partname.compare("Data Manager")==0) + QString partname = part->GetPartName(); + if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkPointBasedRegistrationView* m_View; }; QmitkPointBasedRegistrationView::QmitkPointBasedRegistrationView(QObject * /*parent*/, const char * /*name*/) -: QmitkFunctionality(), m_SelListener(0), m_MultiWidget(NULL), m_FixedLandmarks(NULL), m_MovingLandmarks(NULL), m_MovingNode(NULL), +: QmitkFunctionality(), m_MultiWidget(NULL), m_FixedLandmarks(NULL), m_MovingLandmarks(NULL), m_MovingNode(NULL), m_FixedNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Transformation(0), m_HideFixedImage(false), m_HideMovingImage(false), m_OldFixedLabel(""), m_OldMovingLabel(""), m_Deactivated (false), m_CurrentFixedLandmarksObserverID(0), m_CurrentMovingLandmarksObserverID(0) { m_FixedLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_FixedLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateFixedLandmarksList); m_MovingLandmarksChangedCommand = itk::SimpleMemberCommand::New(); m_MovingLandmarksChangedCommand->SetCallbackFunction(this, &QmitkPointBasedRegistrationView::updateMovingLandmarksList); this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved )); } QmitkPointBasedRegistrationView::~QmitkPointBasedRegistrationView() { - if(m_SelListener.IsNotNull()) + if(m_SelListener) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + if(s) s->RemovePostSelectionListener(m_SelListener.data()); } if (m_FixedPointSetNode.IsNotNull()) { m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } if (m_MovingPointSetNode.IsNotNull()) { m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); } void QmitkPointBasedRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Parent->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); this->CreateConnections(); // let the point set widget know about the multi widget (cross hair updates) m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); m_Controls.m_FixedPointListWidget->SetMultiWidget( m_MultiWidget ); m_Controls.m_MovingPointListWidget->SetMultiWidget( m_MultiWidget ); } void QmitkPointBasedRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; m_Controls.m_FixedPointListWidget->SetMultiWidget( NULL ); m_Controls.m_MovingPointListWidget->SetMultiWidget( NULL ); } void QmitkPointBasedRegistrationView::CreateConnections() { connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_MovingPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), (QObject*)(m_Controls.m_FixedPointListWidget), SLOT(DeactivateInteractor(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideMovingImage(bool))); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(EditPointSets(bool)), this, SLOT(HideFixedImage(bool))); connect( (QObject*)(m_Controls.m_FixedPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateFixedLandmarksList())); connect( (QObject*)(m_Controls.m_MovingPointListWidget), SIGNAL(PointListChanged()), this, SLOT(updateMovingLandmarksList())); connect((QObject*)(m_Controls.m_Calculate),SIGNAL(clicked()),this,SLOT(calculate())); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect((QObject*)(m_Controls.m_UndoTransformation),SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect((QObject*)(m_Controls.m_RedoTransformation),SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect((QObject*)(m_Controls.m_ShowRedGreenValues),SIGNAL(toggled(bool)),this,SLOT(showRedGreen(bool))); connect((QObject*)(m_Controls.m_OpacitySlider),SIGNAL(valueChanged(int)),this,SLOT(OpacityUpdate(int))); connect((QObject*)(m_Controls.m_SelectedTransformationClass),SIGNAL(activated(int)), this,SLOT(transformationChanged(int))); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkCalculateEnabled())); connect((QObject*)(m_Controls.m_UseICP),SIGNAL(toggled(bool)), this,SLOT(checkLandmarkError())); } void QmitkPointBasedRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); this->clearTransformationLists(); - if (m_SelListener.IsNull()) + if (m_SelListener.isNull()) { - m_SelListener = berry::ISelectionListener::Pointer(new SelListenerPointBasedRegistration(this)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + m_SelListener.reset(new SelListenerPointBasedRegistration(this)); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); + static_cast(m_SelListener.data())->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->showRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); } void QmitkPointBasedRegistrationView::Visible() { } void QmitkPointBasedRegistrationView::Deactivated() { m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + if(s) s->RemovePostSelectionListener(m_SelListener.data()); + m_SelListener.reset(); } void QmitkPointBasedRegistrationView::Hidden() { /* m_Deactivated = true; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_Controls.m_FixedPointListWidget->SetPointSetNode(NULL); m_Controls.m_FixedPointListWidget->DeactivateInteractor(true); if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_Controls.m_MovingPointListWidget->SetPointSetNode(NULL); m_Controls.m_MovingPointListWidget->DeactivateInteractor(true); this->setImageColor(false); if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); } this->clearTransformationLists(); if (m_FixedPointSetNode.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_FixedLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_FixedPointSetNode); } if (m_MovingPointSetNode.IsNotNull() && m_MovingLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() == 0) { this->GetDataStorage()->Remove(m_MovingPointSetNode); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_FixedNode = NULL; m_MovingNode = NULL; if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); m_FixedLandmarks = NULL; if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); m_MovingLandmarks = NULL; m_FixedPointSetNode = NULL; m_MovingPointSetNode = NULL; m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkPointBasedRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); m_Controls.m_SwitchImages->hide(); m_Controls.m_ShowRedGreenValues->setEnabled(false); } } void QmitkPointBasedRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if(m_FixedLandmarks.IsNotNull()) m_FixedLandmarks->RemoveObserver(m_CurrentFixedLandmarksObserverID); if (fixedImage.IsNotNull()) { if (m_FixedNode != fixedImage) { // remove changes on previous selected node if (m_FixedNode.IsNotNull()) { this->setImageColor(false); m_FixedNode->SetOpacity(1.0); if (m_FixedPointSetNode.IsNotNull()) { m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); } } // get selected node m_FixedNode = fixedImage; m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.m_FixedLabel->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.m_SwitchImages->show(); m_Controls.TextLabelFixed->show(); m_Controls.line2->show(); m_Controls.m_FixedPointListWidget->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_FixedNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_FixedPointSetNode=children->GetElement(i); m_FixedLandmarks = dynamic_cast (m_FixedPointSetNode->GetData()); this->GetDataStorage()->Remove(m_FixedPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if (m_FixedPointSetNode.IsNull()) { m_FixedLandmarks = mitk::PointSet::New(); m_FixedPointSetNode = mitk::DataNode::New(); m_FixedPointSetNode->SetData(m_FixedLandmarks); m_FixedPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_FixedPointSetNode->GetStringProperty("label", m_OldFixedLabel); m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New("F ")); m_FixedPointSetNode->SetProperty("color", mitk::ColorProperty::New(0.0f, 1.0f, 1.0f)); m_FixedPointSetNode->SetVisibility(true); m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); this->GetDataStorage()->Add(m_FixedPointSetNode, m_FixedNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_FixedNode = NULL; if (m_FixedPointSetNode.IsNotNull()) m_FixedPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldFixedLabel)); m_FixedPointSetNode = NULL; m_FixedLandmarks = NULL; m_Controls.m_FixedPointListWidget->SetPointSetNode(m_FixedPointSetNode); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.line2->hide(); m_Controls.m_FixedPointListWidget->hide(); m_Controls.m_SwitchImages->hide(); } if(m_FixedLandmarks.IsNotNull()) m_CurrentFixedLandmarksObserverID = m_FixedLandmarks->AddObserver(itk::ModifiedEvent(), m_FixedLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if(m_MovingLandmarks.IsNotNull()) m_MovingLandmarks->RemoveObserver(m_CurrentMovingLandmarksObserverID); if (movingImage.IsNotNull()) { if (m_MovingNode != movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->setImageColor(false); if (m_MovingNode != m_FixedNode) { m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); } else { m_OldFixedLabel = m_OldMovingLabel; } } if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingNode = movingImage; m_MovingNode->SetVisibility(true); m_Controls.m_MovingLabel->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); m_Controls.line1->show(); m_Controls.m_MovingPointListWidget->show(); m_Controls.m_OpacityLabel->show(); m_Controls.m_OpacitySlider->show(); m_Controls.label->show(); m_Controls.label_2->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->setImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); bool hasPointSetNode = false; mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { mitk::StringProperty::Pointer nameProp = dynamic_cast(children->GetElement(i)->GetProperty("name")); if(nameProp.IsNotNull() && nameProp->GetValueAsString()=="PointBasedRegistrationNode") { m_MovingPointSetNode=children->GetElement(i); m_MovingLandmarks = dynamic_cast (m_MovingPointSetNode->GetData()); this->GetDataStorage()->Remove(m_MovingPointSetNode); hasPointSetNode = true; break; } } if (!hasPointSetNode) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); } this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->OpacityUpdate(m_Opacity); } if (m_MovingPointSetNode.IsNull()) { m_MovingLandmarks = mitk::PointSet::New(); m_MovingPointSetNode = mitk::DataNode::New(); m_MovingPointSetNode->SetData(m_MovingLandmarks); m_MovingPointSetNode->SetProperty("name", mitk::StringProperty::New("PointBasedRegistrationNode")); m_MovingPointSetNode->GetStringProperty("label", m_OldMovingLabel); m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New("M ")); m_MovingPointSetNode->SetProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f)); m_MovingPointSetNode->SetVisibility(true); m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); this->GetDataStorage()->Add(m_MovingPointSetNode, m_MovingNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } else { m_MovingNode = NULL; if (m_MovingPointSetNode.IsNotNull()) m_MovingPointSetNode->SetProperty("label", mitk::StringProperty::New(m_OldMovingLabel)); m_MovingPointSetNode = NULL; m_MovingLandmarks = NULL; m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.line1->hide(); m_Controls.m_MovingPointListWidget->hide(); m_Controls.m_OpacityLabel->hide(); m_Controls.m_OpacitySlider->hide(); m_Controls.label->hide(); m_Controls.label_2->hide(); } if(m_MovingLandmarks.IsNotNull()) m_CurrentMovingLandmarksObserverID = m_MovingLandmarks->AddObserver(itk::ModifiedEvent(), m_MovingLandmarksChangedCommand); } void QmitkPointBasedRegistrationView::updateMovingLandmarksList() { // mitk::PointSet* ps = mitk::PointSet::New(); // ps = dynamic_cast(m_MovingPointSetNode->GetData()); // mitk::DataNode::Pointer tmpPtr = m_MovingPointSetNode; // m_MovingLandmarks = 0; // m_MovingLandmarks = (ps); m_MovingLandmarks = dynamic_cast(m_MovingPointSetNode->GetData()); // m_Controls.m_MovingPointListWidget->SetPointSetNode(m_MovingPointSetNode); //Workaround: m_MovingPointListWidget->m_PointListView->m_PointListModel loses the pointer on the pointsetnode this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::updateFixedLandmarksList() { m_FixedLandmarks = dynamic_cast(m_FixedPointSetNode->GetData()); this->checkLandmarkError(); this->CheckCalculate(); } void QmitkPointBasedRegistrationView::HideFixedImage(bool hide) { m_HideFixedImage = hide; if(m_FixedNode.IsNotNull()) { m_FixedNode->SetVisibility(!hide); } if (hide) { //this->reinitMovingClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::HideMovingImage(bool hide) { m_HideMovingImage = hide; if(m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(!hide); } if (hide) { //this->reinitFixedClicked(); } if (!m_HideMovingImage && !m_HideFixedImage) { //this->globalReinitClicked(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool QmitkPointBasedRegistrationView::CheckCalculate() { if((m_MovingPointSetNode.IsNull())||(m_FixedPointSetNode.IsNull()||m_FixedLandmarks.IsNull()||m_MovingLandmarks.IsNull())) return false; if(m_MovingNode==m_FixedNode) return false; return this->checkCalculateEnabled(); } void QmitkPointBasedRegistrationView::UndoTransformation() { if(!m_UndoPointsGeometryList.empty()) { mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_RedoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); m_MovingLandmarks->SetGeometry(m_UndoPointsGeometryList.back()); m_UndoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_RedoGeometryList.push_back(movingGeometry.GetPointer()); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeGeometry()->Update(); m_MovingLandmarks->GetTimeGeometry()->Update(); m_Controls.m_RedoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_UndoPointsGeometryList.empty()) { m_Controls.m_UndoTransformation->setEnabled(true); } else { m_Controls.m_UndoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::RedoTransformation() { if(!m_RedoPointsGeometryList.empty()) { mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); m_MovingLandmarks->SetGeometry(m_RedoPointsGeometryList.back()); m_RedoPointsGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingPointSetNode->SetMapper(1, NULL); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(movingGeometry.GetPointer()); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdate(m_MultiWidget->mitkWidget4->GetRenderWindow()); movingData->GetTimeGeometry()->Update(); m_MovingLandmarks->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } if(!m_RedoPointsGeometryList.empty()) { m_Controls.m_RedoTransformation->setEnabled(true); } else { m_Controls.m_RedoTransformation->setEnabled(false); } } void QmitkPointBasedRegistrationView::showRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->setImageColor(m_ShowRedGreen); } void QmitkPointBasedRegistrationView::setImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(float opacity) { if (opacity > 1) { opacity = opacity/100.0f; } m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPointBasedRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkPointBasedRegistrationView::clearTransformationLists() { m_Controls.m_UndoTransformation->setEnabled(false); m_Controls.m_RedoTransformation->setEnabled(false); m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); m_UndoGeometryList.clear(); m_UndoPointsGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); } void QmitkPointBasedRegistrationView::checkLandmarkError() { double totalDist = 0, dist = 0, dist2 = 0; mitk::Point3D point1, point2, point3; double p1[3], p2[3]; if(m_Transformation < 3) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull()&& m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(0); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; dist = vtkMath::Distance2BetweenPoints(p1, p2); for(int pointId2 = 1; pointId2 < m_FixedLandmarks->GetSize(); ++pointId2) { point2 = m_FixedLandmarks->GetPoint(pointId2); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = p1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = p2[2]; dist2 = vtkMath::Distance2BetweenPoints(p1, p2); if (dist2 < dist) { dist = dist2; } } totalDist += dist; } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } else { if (m_MovingLandmarks.IsNotNull() && m_FixedLandmarks.IsNotNull() && m_MovingLandmarks->GetSize() != 0 && m_FixedLandmarks->GetSize() != 0 && m_MovingLandmarks->GetSize() == m_FixedLandmarks->GetSize()) { for(int pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { point1 = m_MovingLandmarks->GetPoint(pointId); point2 = m_FixedLandmarks->GetPoint(pointId); p1[0] = point1[0]; p1[1] = point1[1]; p1[2] = point1[2]; p2[0] = point2[0]; p2[1] = point2[1]; p2[2] = point2[2]; totalDist += vtkMath::Distance2BetweenPoints(p1, p2); } m_Controls.m_MeanErrorLCD->display(sqrt(totalDist/m_FixedLandmarks->GetSize())); m_Controls.m_MeanErrorLCD->show(); m_Controls.m_MeanError->show(); } else { m_Controls.m_MeanErrorLCD->hide(); m_Controls.m_MeanError->hide(); } } } void QmitkPointBasedRegistrationView::transformationChanged(int transform) { m_Transformation = transform; this->checkCalculateEnabled(); this->checkLandmarkError(); } // ICP with vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbasedWithICP() { if(CheckCalculate()) { mitk::BaseGeometry::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(originalDataGeometry.GetPointer()); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); vtkCellArray* vCellsSource=vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointSource=m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(pointSource[0],pointSource[1],pointSource[2]); vCellsSource->InsertNextCell(1, &pointId); } vtkPoints* vPointsTarget=vtkPoints::New(); vtkCellArray* vCellsTarget = vtkCellArray::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D pointTarget=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(pointTarget[0],pointTarget[1],pointTarget[2]); vCellsTarget->InsertNextCell(1, &pointId); } vtkPolyData* vPointSetSource=vtkPolyData::New(); vtkPolyData* vPointSetTarget=vtkPolyData::New(); vPointSetTarget->SetPoints(vPointsTarget); vPointSetTarget->SetVerts(vCellsTarget); vPointSetSource->SetPoints(vPointsSource); vPointSetSource->SetVerts(vCellsSource); vtkIterativeClosestPointTransform * icp=vtkIterativeClosestPointTransform::New(); icp->SetCheckMeanDistance(1); icp->SetSource(vPointSetSource); icp->SetTarget(vPointSetTarget); icp->SetMaximumNumberOfIterations(50); icp->StartByMatchingCentroidsOn(); vtkLandmarkTransform * transform=icp->GetLandmarkTransform(); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=icp->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated by ICP.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeGeometry()->Update(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } // only vtkLandmarkTransformation void QmitkPointBasedRegistrationView::calculateLandmarkbased() { if(CheckCalculate()) { mitk::BaseGeometry::Pointer pointsGeometry = m_MovingLandmarks->GetGeometry(0); mitk::BaseGeometry::Pointer movingLandmarksGeometry = m_MovingLandmarks->GetGeometry(0)->Clone(); m_UndoPointsGeometryList.push_back(movingLandmarksGeometry.GetPointer()); mitk::BaseData::Pointer originalData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer originalDataGeometry = originalData->GetGeometry(0)->Clone(); m_UndoGeometryList.push_back(originalDataGeometry.GetPointer()); vtkIdType pointId; vtkPoints* vPointsSource=vtkPoints::New(); for(pointId = 0; pointId < m_MovingLandmarks->GetSize(); ++pointId) { mitk::Point3D sourcePoint = m_MovingLandmarks->GetPoint(pointId); vPointsSource->InsertNextPoint(sourcePoint[0],sourcePoint[1],sourcePoint[2]); } vtkPoints* vPointsTarget=vtkPoints::New(); for(pointId=0; pointIdGetSize();++pointId) { mitk::Point3D targetPoint=m_FixedLandmarks->GetPoint(pointId); vPointsTarget->InsertNextPoint(targetPoint[0],targetPoint[1],targetPoint[2]); } vtkLandmarkTransform * transform= vtkLandmarkTransform::New(); transform->SetSourceLandmarks(vPointsSource); transform->SetTargetLandmarks(vPointsTarget); if(m_Transformation==0) { transform->SetModeToRigidBody(); } if(m_Transformation==1) { transform->SetModeToSimilarity(); } if(m_Transformation==2) { transform->SetModeToAffine(); } vtkMatrix4x4 * matrix=transform->GetMatrix(); double determinant = fabs(matrix->Determinant()); if((determinant < mitk::eps) || (determinant > 100) || (determinant < 0.01) || (determinant==itk::NumericTraits::infinity()) || (determinant==itk::NumericTraits::quiet_NaN()) || (determinant==itk::NumericTraits::signaling_NaN()) || (determinant==-itk::NumericTraits::infinity()) || (determinant==-itk::NumericTraits::quiet_NaN()) || (determinant==-itk::NumericTraits::signaling_NaN()) || (!(determinant <= 0) && !(determinant > 0))) { QMessageBox msgBox; msgBox.setText("Suspicious determinant of matrix calculated.\n" "Please select more points or other points!" ); msgBox.exec(); return; } pointsGeometry->Compose(matrix); m_MovingLandmarks->GetTimeGeometry()->Update(); mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); mitk::BaseGeometry::Pointer movingGeometry = movingData->GetGeometry(0); movingGeometry->Compose(matrix); movingData->GetTimeGeometry()->Update(); m_Controls.m_UndoTransformation->setEnabled(true); m_Controls.m_RedoTransformation->setEnabled(false); m_RedoGeometryList.clear(); m_RedoPointsGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->checkLandmarkError(); } } void QmitkPointBasedRegistrationView::calculateLandmarkWarping() { mitk::LandmarkWarping* registration = new mitk::LandmarkWarping(); mitk::LandmarkWarping::FixedImageType::Pointer fixedImage = mitk::LandmarkWarping::FixedImageType::New(); mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData()); mitk::LandmarkWarping::MovingImageType::Pointer movingImage = mitk::LandmarkWarping::MovingImageType::New(); mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData()); if (fimage.IsNotNull() && /*fimage->GetDimension() == 2 || */ fimage->GetDimension() == 3 && mimage.IsNotNull() && mimage->GetDimension() == 3) { mitk::CastToItkImage(fimage, fixedImage); mitk::CastToItkImage(mimage, movingImage); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImage); unsigned int pointId; mitk::Point3D sourcePoint, targetPoint; mitk::LandmarkWarping::LandmarkContainerType::Pointer fixedLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); mitk::LandmarkWarping::LandmarkPointType point; for(pointId = 0; pointId < (unsigned int)m_FixedLandmarks->GetSize(); ++pointId) { fimage->GetGeometry(0)->WorldToItkPhysicalPoint(m_FixedLandmarks->GetPoint(pointId), point); fixedLandmarks->InsertElement( pointId, point); } mitk::LandmarkWarping::LandmarkContainerType::Pointer movingLandmarks = mitk::LandmarkWarping::LandmarkContainerType::New(); for(pointId = 0; pointId < (unsigned int)m_MovingLandmarks->GetSize(); ++pointId) { mitk::BaseData::Pointer fixedData = m_FixedNode->GetData(); mitk::BaseGeometry::Pointer fixedGeometry = fixedData->GetGeometry(0); fixedGeometry->WorldToItkPhysicalPoint(m_MovingLandmarks->GetPoint(pointId), point); movingLandmarks->InsertElement( pointId, point); } registration->SetLandmarks(fixedLandmarks.GetPointer(), movingLandmarks.GetPointer()); mitk::LandmarkWarping::MovingImageType::Pointer output = registration->Register(); if (output.IsNotNull()) { mitk::Image::Pointer image = mitk::Image::New(); mitk::CastToMitkImage(output, image); m_MovingNode->SetData(image); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelWindow; levelWindow.SetAuto( image ); levWinProp->SetLevelWindow(levelWindow); m_MovingNode->GetPropertyList()->SetProperty("levelwindow",levWinProp); movingLandmarks = registration->GetTransformedTargetLandmarks(); mitk::PointSet::PointDataIterator it; it = m_MovingLandmarks->GetPointSet()->GetPointData()->Begin(); //increase the eventId to encapsulate the coming operations mitk::OperationEvent::IncCurrObjectEventId(); mitk::OperationEvent::ExecuteIncrement(); for(pointId=0; pointIdSize();++pointId, ++it) { int position = it->Index(); mitk::PointSet::PointType pt = m_MovingLandmarks->GetPoint(position); mitk::Point3D undoPoint = ( pt ); point = movingLandmarks->GetElement(pointId); fimage->GetGeometry(0)->ItkPhysicalPointToWorld(point, pt); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVE, pt, position); //undo operation mitk::PointOperation* undoOp = new mitk::PointOperation(mitk::OpMOVE, undoPoint, position); mitk::OperationEvent* operationEvent = new mitk::OperationEvent(m_MovingLandmarks, doOp, undoOp, "Move point"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent(operationEvent); //execute the Operation m_MovingLandmarks->ExecuteOperation(doOp); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->clearTransformationLists(); this->checkLandmarkError(); } } } bool QmitkPointBasedRegistrationView::checkCalculateEnabled() { if (m_FixedLandmarks.IsNotNull() && m_MovingLandmarks.IsNotNull()) { int fixedPoints = m_FixedLandmarks->GetSize(); int movingPoints = m_MovingLandmarks->GetSize(); if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if((movingPoints > 0 && fixedPoints > 0)) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } else { if ((movingPoints == fixedPoints) && movingPoints > 0) { m_Controls.m_Calculate->setEnabled(true); return true; } else { m_Controls.m_Calculate->setEnabled(false); return false; } } } else { m_Controls.m_Calculate->setEnabled(true); return true; } } else { return false; } } void QmitkPointBasedRegistrationView::calculate() { if (m_Transformation == 0 || m_Transformation == 1 || m_Transformation == 2) { if (m_Controls.m_UseICP->isChecked()) { if (m_MovingLandmarks->GetSize() == 1 && m_FixedLandmarks->GetSize() == 1) { this->calculateLandmarkbased(); } else { this->calculateLandmarkbasedWithICP(); } } else { this->calculateLandmarkbased(); } } else { this->calculateLandmarkWarping(); } } void QmitkPointBasedRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h index 1f10306448..2112045989 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkPointBasedRegistrationView.h @@ -1,292 +1,292 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #if !defined(QMITK_POINTBASEDREGISTRATION_H__INCLUDED) #define QMITK_POINTBASEDREGISTRATION_H__INCLUDED #include "QmitkFunctionality.h" #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" //#include "mitkTestingConfig.h" // IMPORTANT: this defines or undefines BUILD_TESTING ! #include #include #include //#include "QmitkMessageBoxHelper.h" #include "ui_QmitkPointBasedRegistrationViewControls.h" #include /*! \brief The PointBasedRegistration functionality is used to perform point based registration. This functionality allows you to register 2D as well as 3D images in a rigid and deformable manner via corresponding PointSets. Register means to align two images, so that they become as similar as possible. Therefore you have to set corresponding points in both images, which will be matched. The movement, which has to be performed on the points to align them will be performed on the moving image as well. The result is shown in the multi-widget. For more informations see: \ref QmitkPointBasedRegistrationUserManual \sa QmitkFunctionality \ingroup Functionalities \ingroup PointBasedRegistration */ class REGISTRATION_EXPORT QmitkPointBasedRegistrationView : public QmitkFunctionality { friend struct SelListenerPointBasedRegistration; Q_OBJECT public: static const std::string VIEW_ID; /*! \brief Default constructor */ QmitkPointBasedRegistrationView(QObject *parent=0, const char *name=0); /*! \brief Default destructor */ virtual ~QmitkPointBasedRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief Method for creating the connections of main and control widget */ virtual void CreateConnections(); virtual void Activated(); virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); // // #ifdef BUILD_TESTING // / ** // \brief Testing entry point // * / // virtual int TestYourself(); // // / ** // \brief Helper method for testing // * / // bool TestAllTools(); // // // protected slots: // /** // \brief Helper method for testing // */ // void RegistrationErrorDialogFound( QWidget* widget ); // // /** // \brief Helper method for testing // */ // void ClearPointSetDialogFound( QWidget* widget ); // // private: // bool m_MessageBox; // // // public: // #else // // slot function is needed, because moc ignores our #ifdefs // void RegistrationErrorDialogFound( QWidget* widget ) {} // // slot function is needed, because moc ignores our #ifdefs // void ClearPointSetDialogFound(QWidget* widget){} // #endif void DataNodeHasBeenRemoved(const mitk::DataNode* node); protected slots: /*! \brief Sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! \brief Sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! \brief Calculates registration with vtkLandmarkTransform */ void calculateLandmarkbased(); /*! \brief Calculates registration with itkLandmarkWarping */ void calculateLandmarkWarping(); /*! \brief Calculates registration with ICP and vtkLandmarkTransform */ void calculateLandmarkbasedWithICP(); /*! \brief lets the fixed image become invisible and the moving image visible */ void HideMovingImage(bool hide); /*! \brief lets the moving image become invisible and the fixed image visible */ void HideFixedImage(bool hide); /*! \brief Checks if registration is possible */ bool CheckCalculate(); /*! \brief Performs an undo for the last transform. */ void UndoTransformation(); /*! \brief Performs a redo for the last undo transform. */ void RedoTransformation(); /*! \brief Stores whether the image will be shown in grayvalues or in red for fixed image and green for moving image @param show if true, then images will be shown in red and green */ void showRedGreen(bool show); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! \brief Updates the moving landmarks */ void updateMovingLandmarksList(); /*! \brief Updates the fixed landmarks */ void updateFixedLandmarksList(); /*! \brief Sets the images to gray values or fixed image to red and moving image to green @param redGreen if true, then images will be shown in red and green */ void setImageColor(bool redGreen); /*! \brief Clears the undo and redo transformation lists. */ void clearTransformationLists(); /*! \brief Calculates the landmark error for the selected transformation. */ void checkLandmarkError(); /*! \brief Changes the transformation type and calls checkLandmarkError(). */ void transformationChanged(int transform); /*! \brief Checks whether the registration can be performed. */ bool checkCalculateEnabled(); /*! \brief Performs the registration. */ void calculate(); void SwitchImages(); protected: - berry::ISelectionListener::Pointer m_SelListener; + QScopedPointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for point based registration */ Ui::QmitkPointBasedRegistrationControls m_Controls; mitk::PointSet::Pointer m_FixedLandmarks; mitk::PointSet::Pointer m_MovingLandmarks; mitk::DataNode::Pointer m_MovingPointSetNode; mitk::DataNode::Pointer m_FixedPointSetNode; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_FixedNode; std::list m_UndoGeometryList; std::list m_UndoPointsGeometryList; std::list m_RedoGeometryList; std::list m_RedoPointsGeometryList; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; mitk::Color m_FixedColor; mitk::Color m_MovingColor; int m_Transformation; bool m_HideFixedImage; bool m_HideMovingImage; std::string m_OldFixedLabel; std::string m_OldMovingLabel; bool m_Deactivated; int m_CurrentFixedLandmarksObserverID; int m_CurrentMovingLandmarksObserverID; itk::SimpleMemberCommand::Pointer m_FixedLandmarksChangedCommand; itk::SimpleMemberCommand::Pointer m_MovingLandmarksChangedCommand; }; #endif // !defined(QMITK_POINTBASEDREGISTRATION_H__INCLUDED) diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp index 8c287ae903..c7dad79144 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.cpp @@ -1,1467 +1,1465 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk includes #include "QmitkRigidRegistrationView.h" #include "QmitkStdMultiWidget.h" // MITK includes #include "mitkDataNodeObject.h" #include #include "mitkManualSegmentationToSurfaceFilter.h" #include #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateProperty.h" // QT includes #include "qinputdialog.h" #include "qmessagebox.h" #include "qcursor.h" #include "qapplication.h" #include "qradiobutton.h" #include "qslider.h" #include "qtooltip.h" // VTK includes #include // ITK includes #include // BlueBerry includes #include "berryIWorkbenchWindow.h" #include "berryISelectionService.h" const std::string QmitkRigidRegistrationView::VIEW_ID = "org.mitk.views.rigidregistration"; using namespace berry; struct SelListenerRigidRegistration : ISelectionListener { berryObjectMacro(SelListenerRigidRegistration); SelListenerRigidRegistration(QmitkRigidRegistrationView* view) { m_View = view; } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); // do something with the selected items if(m_View->m_CurrentSelection) { if (m_View->m_CurrentSelection->Size() != 2) { if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); m_View->m_Controls.TextLabelFixed->hide(); m_View->m_Controls.m_FixedLabel->hide(); m_View->m_Controls.TextLabelMoving->hide(); m_View->m_Controls.m_MovingLabel->hide(); m_View->m_Controls.m_UseMaskingCB->hide(); m_View->m_Controls.m_OpacityLabel->setEnabled(false); m_View->m_Controls.m_OpacitySlider->setEnabled(false); m_View->m_Controls.label->setEnabled(false); m_View->m_Controls.label_2->setEnabled(false); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(false); m_View->m_Controls.m_SwitchImages->hide(); } } else { m_View->m_Controls.m_StatusLabel->hide(); bool foundFixedImage = false; mitk::DataNode::Pointer fixedNode; // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { if (dynamic_cast(node->GetData())->GetDimension() == 4) { m_View->m_Controls.m_StatusLabel->show(); QMessageBox::information( NULL, "RigidRegistration", "Only 2D or 3D images can be processed.", QMessageBox::Ok ); return; } if (foundFixedImage == false) { fixedNode = node; foundFixedImage = true; } else { // m_View->SetImagesVisible(selection); m_View->FixedSelected(fixedNode); m_View->MovingSelected(node); m_View->m_Controls.m_StatusLabel->hide(); m_View->m_Controls.TextLabelFixed->show(); m_View->m_Controls.m_FixedLabel->show(); m_View->m_Controls.TextLabelMoving->show(); m_View->m_Controls.m_MovingLabel->show(); m_View->m_Controls.m_UseMaskingCB->show(); m_View->m_Controls.m_OpacityLabel->setEnabled(true); m_View->m_Controls.m_OpacitySlider->setEnabled(true); m_View->m_Controls.label->setEnabled(true); m_View->m_Controls.label_2->setEnabled(true); m_View->m_Controls.m_ShowRedGreenValues->setEnabled(true); } } else { m_View->m_Controls.m_StatusLabel->show(); return; } } } } } else if (m_View->m_FixedNode.IsNull() || m_View->m_MovingNode.IsNull()) { m_View->m_Controls.m_StatusLabel->show(); } } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& selection) override { // check, if selection comes from datamanager if (part) { - QString partname(part->GetPartName().c_str()); - if(partname.compare("Data Manager")==0) + QString partname = part->GetPartName(); + if(partname == "Data Manager") { // apply selection DoSelectionChanged(selection); } } } QmitkRigidRegistrationView* m_View; }; QmitkRigidRegistrationView::QmitkRigidRegistrationView(QObject * /*parent*/, const char * /*name*/) : QmitkFunctionality(), m_MultiWidget(NULL), m_MovingNode(NULL), m_MovingMaskNode(NULL), m_FixedNode(NULL), m_FixedMaskNode(NULL), m_ShowRedGreen(false), m_Opacity(0.5), m_OriginalOpacity(1.0), m_Deactivated(false),m_FixedDimension(0), m_MovingDimension(0) { m_TranslateSliderPos[0] = 0; m_TranslateSliderPos[1] = 0; m_TranslateSliderPos[2] = 0; m_RotateSliderPos[0] = 0; m_RotateSliderPos[1] = 0; m_RotateSliderPos[2] = 0; m_ScaleSliderPos[0] = 0; m_ScaleSliderPos[1] = 0; m_ScaleSliderPos[2] = 0; translationParams = new int[3]; rotationParams = new int[3]; scalingParams = new int[3]; m_TimeStepperAdapter = NULL; this->GetDataStorage()->RemoveNodeEvent.AddListener(mitk::MessageDelegate1 ( this, &QmitkRigidRegistrationView::DataNodeHasBeenRemoved )); } QmitkRigidRegistrationView::~QmitkRigidRegistrationView() { - if(m_SelListener.IsNotNull()) + if(m_SelListener) { berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + if(s) s->RemovePostSelectionListener(m_SelListener.data()); } this->GetDataStorage()->RemoveNodeEvent.RemoveListener(mitk::MessageDelegate1 ( this, &QmitkRigidRegistrationView::DataNodeHasBeenRemoved )); } void QmitkRigidRegistrationView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.m_ManualFrame->hide(); m_Controls.timeSlider->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); //m_Controls.m_UseFixedImageMask->hide(); //m_Controls.m_UseMovingImageMask->hide(); m_Controls.m_UseMaskingCB->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); if (m_Controls.m_RigidTransform->currentIndex() == 1) { m_Controls.frame->show(); } else { m_Controls.frame->hide(); } m_Controls.m_ManualFrame->setEnabled(false); m_Parent->setEnabled(false); mitk::NodePredicateAnd::Pointer andPred = // we want binary images in the selectors mitk::NodePredicateAnd::New(mitk::NodePredicateDataType::New("Image"), mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true))); m_Controls.m_FixedImageCB->SetPredicate(andPred); m_Controls.m_FixedImageCB->SetDataStorage(this->GetDataStorage()); m_Controls.m_FixedImageCB->hide(); m_Controls.m_FixedMaskLB->hide(); m_Controls.m_MovingImageCB->SetPredicate(andPred); m_Controls.m_MovingImageCB->SetDataStorage(this->GetDataStorage()); m_Controls.m_MovingImageCB->hide(); m_Controls.m_MovingMaskLB->hide(); this->CreateConnections(); this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_Parent->setEnabled(true); m_MultiWidget = &stdMultiWidget; m_MultiWidget->SetWidgetPlanesVisibility(true); } void QmitkRigidRegistrationView::StdMultiWidgetNotAvailable() { m_Parent->setEnabled(false); m_MultiWidget = NULL; } void QmitkRigidRegistrationView::CreateConnections() { connect( m_Controls.m_ManualRegistrationCheckbox, SIGNAL(toggled(bool)), this, SLOT(ShowManualRegistrationFrame(bool))); connect((QObject*)(m_Controls.m_SwitchImages),SIGNAL(clicked()),this,SLOT(SwitchImages())); connect(m_Controls.m_ShowRedGreenValues, SIGNAL(toggled(bool)), this, SLOT(ShowRedGreen(bool))); connect(m_Controls.m_ShowContour, SIGNAL(toggled(bool)), this, SLOT(EnableContour(bool))); //connect(m_Controls.m_UseFixedImageMask, SIGNAL(toggled(bool)), this, SLOT(UseFixedMaskImageChecked(bool))); //connect(m_Controls.m_UseMovingImageMask, SIGNAL(toggled(bool)), this, SLOT(UseMovingMaskImageChecked(bool))); connect(m_Controls.m_RigidTransform, SIGNAL(currentChanged(int)), this, SLOT(TabChanged(int))); connect(m_Controls.m_OpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityUpdate(int))); connect(m_Controls.m_ContourSlider, SIGNAL(sliderReleased()), this, SLOT(ShowContour())); connect(m_Controls.m_CalculateTransformation, SIGNAL(clicked()), this, SLOT(Calculate())); connect(m_Controls.m_UndoTransformation,SIGNAL(clicked()),this,SLOT(UndoTransformation())); connect(m_Controls.m_RedoTransformation,SIGNAL(clicked()),this,SLOT(RedoTransformation())); connect(m_Controls.m_AutomaticTranslation,SIGNAL(clicked()),this,SLOT(AlignCenters())); connect(m_Controls.m_StopOptimization,SIGNAL(clicked()), this , SLOT(StopOptimizationClicked())); connect(m_Controls.m_XTransSlider, SIGNAL(valueChanged(int)), this, SLOT(xTrans_valueChanged(int))); connect(m_Controls.m_YTransSlider, SIGNAL(valueChanged(int)), this, SLOT(yTrans_valueChanged(int))); connect(m_Controls.m_ZTransSlider, SIGNAL(valueChanged(int)), this, SLOT(zTrans_valueChanged(int))); connect(m_Controls.m_XRotSlider, SIGNAL(valueChanged(int)), this, SLOT(xRot_valueChanged(int))); connect(m_Controls.m_YRotSlider, SIGNAL(valueChanged(int)), this, SLOT(yRot_valueChanged(int))); connect(m_Controls.m_ZRotSlider, SIGNAL(valueChanged(int)), this, SLOT(zRot_valueChanged(int))); connect(m_Controls.m_XScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(xScale_valueChanged(int))); connect(m_Controls.m_YScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(yScale_valueChanged(int))); connect(m_Controls.m_ZScaleSlider, SIGNAL(valueChanged(int)), this, SLOT(zScale_valueChanged(int))); connect(m_Controls.m_LoadRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationParameter())); connect(m_Controls.m_SaveRigidRegistrationParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationParameter())); connect(m_Controls.m_LoadRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(LoadRigidRegistrationTestParameter())); connect(m_Controls.m_SaveRigidRegistrationTestParameter, SIGNAL(clicked()), m_Controls.qmitkRigidRegistrationSelector1, SLOT(SaveRigidRegistrationTestParameter())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(OptimizerChanged(double)),this,SLOT(SetOptimizerValue( double ))); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(TransformChanged()),this,SLOT(CheckCalculateEnabled())); connect(m_Controls.qmitkRigidRegistrationSelector1,SIGNAL(AddNewTransformationToUndoList()),this,SLOT(AddNewTransformationToUndoList())); connect(m_Controls.m_UseMaskingCB, SIGNAL(stateChanged(int)),this,SLOT(OnUseMaskingChanged(int))); connect(m_Controls.m_FixedImageCB, SIGNAL(OnSelectionChanged(const mitk::DataNode*)),this,SLOT(OnFixedMaskImageChanged(const mitk::DataNode*))); connect(m_Controls.m_MovingImageCB, SIGNAL(OnSelectionChanged(const mitk::DataNode*)),this,SLOT(OnMovingMaskImageChanged(const mitk::DataNode*))); } void QmitkRigidRegistrationView::Activated() { m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); - if (m_SelListener.IsNull()) + if (m_SelListener.isNull()) { - m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); + m_SelListener.reset(new SelListenerRigidRegistration(this)); + this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener.data()); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); + static_cast(m_SelListener.data())->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled(); /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/ *"org.mitk.views.datamanager",* / m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Visible() { /* m_Deactivated = false; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Activated(); if (m_SelListener.IsNull()) { m_SelListener = berry::ISelectionListener::Pointer(new SelListenerRigidRegistration(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener("org.mitk.views.datamanager", m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); } this->OpacityUpdate(m_Controls.m_OpacitySlider->value()); this->ShowRedGreen(m_Controls.m_ShowRedGreenValues->isChecked()); this->ClearTransformationLists(); this->CheckCalculateEnabled();*/ } void QmitkRigidRegistrationView::Deactivated() { m_Deactivated = true; this->SetImageColor(false); if (m_FixedNode.IsNotNull()) m_FixedNode->SetOpacity(1.0); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - if(s) - s->RemovePostSelectionListener(m_SelListener); - m_SelListener = NULL; + if(s) s->RemovePostSelectionListener(m_SelListener.data()); + m_SelListener.reset(); /* m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::Hidden() { /*m_Deactivated = true; this->SetImageColor(false); m_FixedNode = NULL; m_MovingNode = NULL; this->ClearTransformationLists(); berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); if(s) s->RemovePostSelectionListener(m_SelListener); m_SelListener = NULL; //mitk::RenderingManager::GetInstance()->RequestUpdateAll(); //QmitkFunctionality::Deactivated();*/ } void QmitkRigidRegistrationView::DataNodeHasBeenRemoved(const mitk::DataNode* node) { if(node == m_FixedNode || node == m_MovingNode) { m_Controls.m_StatusLabel->show(); m_Controls.TextLabelFixed->hide(); m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_MovingLabel->hide(); m_Controls.m_OpacityLabel->setEnabled(false); m_Controls.m_OpacitySlider->setEnabled(false); m_Controls.label->setEnabled(false); m_Controls.label_2->setEnabled(false); m_Controls.m_ShowRedGreenValues->setEnabled(false); m_Controls.m_SwitchImages->hide(); } else if(node == m_ContourHelperNode) { // can this cause a memory leak? m_ContourHelperNode = NULL; } } void QmitkRigidRegistrationView::FixedSelected(mitk::DataNode::Pointer fixedImage) { if (m_FixedNode.IsNotNull()) { this->SetImageColor(false); m_FixedNode->SetOpacity(1.0); } m_FixedNode = fixedImage; if (m_FixedNode.IsNotNull()) { m_FixedNode->SetOpacity(0.5); m_FixedNode->SetVisibility(true); m_Controls.TextLabelFixed->setText(QString::fromStdString(m_FixedNode->GetName())); m_Controls.m_FixedLabel->show(); m_Controls.TextLabelFixed->show(); m_Controls.m_SwitchImages->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_FixedNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_FixedColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (dynamic_cast(m_FixedNode->GetData())) { m_FixedDimension = dynamic_cast(m_FixedNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetFixedDimension(m_FixedDimension); m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); } // what's about masking? m_Controls.m_UseMaskingCB->show(); // Modify slider range mitk::Image::Pointer image = dynamic_cast(m_FixedNode->GetData()); int min = (int)image->GetStatistics()->GetScalarValueMin(); int max = (int)image->GetStatistics()->GetScalarValueMax(); m_Controls.m_ContourSlider->setRange(min, max); // Set slider to a default value int avg = (min+max) / 2; m_Controls.m_ContourSlider->setSliderPosition(avg); m_Controls.m_ThresholdLabel->setText(QString::number(avg)); } else { m_Controls.m_FixedLabel->hide(); m_Controls.TextLabelFixed->hide(); m_Controls.m_SwitchImages->hide(); } this->CheckCalculateEnabled(); if(this->GetActiveStdMultiWidget()) { m_TimeStepperAdapter = new QmitkStepperAdapter((QObject*) m_Controls.timeSlider, m_MultiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromRigidRegistration"); connect( m_TimeStepperAdapter, SIGNAL( Refetch() ), this, SLOT( UpdateTimestep() ) ); } } void QmitkRigidRegistrationView::MovingSelected(mitk::DataNode::Pointer movingImage) { if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_OriginalOpacity); if (m_FixedNode == m_MovingNode) m_FixedNode->SetOpacity(0.5); this->SetImageColor(false); } // selection did not change - do onot reset if( m_MovingNode.IsNotNull() && m_MovingNode == movingImage) { } else { m_MovingNode = movingImage; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetVisibility(true); m_Controls.TextLabelMoving->setText(QString::fromStdString(m_MovingNode->GetName())); m_Controls.m_MovingLabel->show(); m_Controls.TextLabelMoving->show(); mitk::ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(m_MovingNode->GetProperty("color")); if ( colorProperty.IsNotNull() ) { m_MovingColor = colorProperty->GetColor(); } this->SetImageColor(m_ShowRedGreen); m_MovingNode->GetFloatProperty("opacity", m_OriginalOpacity); this->OpacityUpdate(m_Opacity); // what's about masking? m_Controls.m_UseMaskingCB->show(); } else { m_Controls.m_MovingLabel->hide(); m_Controls.TextLabelMoving->hide(); m_Controls.m_UseMaskingCB->hide(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->MovingImageChanged(); this->CheckCalculateEnabled(); } } bool QmitkRigidRegistrationView::CheckCalculate() { if(m_MovingNode==m_FixedNode) return false; return true; } void QmitkRigidRegistrationView::AddNewTransformationToUndoList() { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry()->Clone().GetPointer())); GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); if(children.IsNotNull() && children->Size() != 0) { unsigned long size; size = children->Size(); for (unsigned long i = 0; i < size; ++i) { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_UndoChildGeometryList.push_back(childGeometries); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); this->SetUndoEnabled(true); this->SetRedoEnabled(false); } void QmitkRigidRegistrationView::UndoTransformation() { if(!m_UndoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_RedoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size = 0; GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { ++size; } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size += children->Size(); for (unsigned long i = 0; i < size; ++i) { if(i==0) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } else { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_RedoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_UndoGeometryList.back()); m_UndoGeometryList.pop_back(); GeometryMapType oldChildGeometries; oldChildGeometries = m_UndoChildGeometryList.back(); m_UndoChildGeometryList.pop_back(); GeometryMapType::iterator iter; for (unsigned long j = 0; j < size; ++j) { if(j == 0) // we have put the geometry for the moving mask at position one { iter = oldChildGeometries.find(m_MovingMaskNode); mitk::Geometry3D* geo = static_cast((*iter).second); m_MovingMaskNode->GetData()->SetGeometry(geo); m_MovingMaskNode->GetData()->GetTimeGeometry()->Update(); } else { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } } //\FIXME when geometry is substituted the matrix referenced by the actor created by the mapper //is still pointing to the old one. Workaround: delete mapper //m_MovingNode->SetMapper(1, NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->SetRedoEnabled(true); } if(!m_UndoGeometryList.empty()) { this->SetUndoEnabled(true); } else { this->SetUndoEnabled(false); } this->CheckCalculateEnabled(); } void QmitkRigidRegistrationView::RedoTransformation() { if(!m_RedoGeometryList.empty()) { mitk::BaseData::Pointer movingData = m_MovingNode->GetData(); m_UndoGeometryList.push_back(static_cast(movingData->GetGeometry(0)->Clone().GetPointer())); unsigned long size = 0; GeometryMapType childGeometries = GeometryMapType(); if(m_MovingMaskNode.IsNotNull()) { ++size; } mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); size += children->Size(); for (unsigned long i = 0; i < size; ++i) { if(i == 0) { childGeometries.insert(std::pair(m_MovingMaskNode, static_cast(m_MovingMaskNode->GetData()->GetGeometry()->Clone().GetPointer()))); } else { childGeometries.insert(std::pair(children->GetElement(i), static_cast(children->GetElement(i)->GetData()->GetGeometry()->Clone().GetPointer()))); } } m_UndoChildGeometryList.push_back(childGeometries); movingData->SetGeometry(m_RedoGeometryList.back()); m_RedoGeometryList.pop_back(); GeometryMapType oldChildGeometries; oldChildGeometries = m_RedoChildGeometryList.back(); m_RedoChildGeometryList.pop_back(); GeometryMapType::iterator iter; for (unsigned long j = 0; j < size; ++j) { if(j == 0) { iter = oldChildGeometries.find(m_MovingMaskNode); m_MovingMaskNode->GetData()->SetGeometry((*iter).second); } else { iter = oldChildGeometries.find(children->GetElement(j)); children->GetElement(j)->GetData()->SetGeometry((*iter).second); } } movingData->GetTimeGeometry()->Update(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); this->SetUndoEnabled(true); } if(!m_RedoGeometryList.empty()) { this->SetRedoEnabled(true); } else { this->SetRedoEnabled(false); } } void QmitkRigidRegistrationView::ShowRedGreen(bool redGreen) { m_ShowRedGreen = redGreen; this->SetImageColor(m_ShowRedGreen); } void QmitkRigidRegistrationView::EnableContour(bool show) { if(show) ShowContour(); // Can happen when the m_ContourHelperNode was deleted before and now the show contour checkbox is turned off if(m_ContourHelperNode.IsNull()) return; m_Controls.m_ContourSlider->setEnabled(show); m_ContourHelperNode->SetProperty("visible", mitk::BoolProperty::New(show)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkRigidRegistrationView::ShowContour() { int threshold = m_Controls.m_ContourSlider->value(); bool show = m_Controls.m_ShowContour->isChecked(); if(m_FixedNode.IsNull() || !show) return; // Update the label next to the slider m_Controls.m_ThresholdLabel->setText(QString::number(threshold)); mitk::Image::Pointer image = dynamic_cast(m_FixedNode->GetData()); typedef itk::Image FloatImageType; typedef itk::Image ShortImageType; // Create a binary image using the given treshold typedef itk::BinaryThresholdImageFilter ThresholdFilterType; FloatImageType::Pointer floatImage = FloatImageType::New(); mitk::CastToItkImage(image, floatImage); ThresholdFilterType::Pointer thresholdFilter = ThresholdFilterType::New(); thresholdFilter->SetInput(floatImage); thresholdFilter->SetLowerThreshold(threshold); thresholdFilter->SetUpperThreshold((int)image->GetStatistics()->GetScalarValueMax()); thresholdFilter->SetInsideValue(1); thresholdFilter->SetOutsideValue(0); thresholdFilter->Update(); ShortImageType::Pointer binaryImage = thresholdFilter->GetOutput(); mitk::Image::Pointer mitkBinaryImage = mitk::Image::New(); mitk::CastToMitkImage(binaryImage, mitkBinaryImage); // Create a contour from the binary image mitk::ManualSegmentationToSurfaceFilter::Pointer surfaceFilter = mitk::ManualSegmentationToSurfaceFilter::New(); surfaceFilter->SetInput( mitkBinaryImage ); surfaceFilter->SetThreshold( 1 ); //expects binary image with zeros and ones surfaceFilter->SetUseGaussianImageSmooth(false); // apply gaussian to thresholded image ? surfaceFilter->SetMedianFilter3D(false); // apply median to segmentation before marching cubes ? surfaceFilter->SetDecimate( mitk::ImageToSurfaceFilter::NoDecimation ); surfaceFilter->UpdateLargestPossibleRegion(); // calculate normals for nicer display mitk::Surface::Pointer surface = surfaceFilter->GetOutput(); if(m_ContourHelperNode.IsNull()) { m_ContourHelperNode = mitk::DataNode::New(); m_ContourHelperNode->SetData(surface); m_ContourHelperNode->SetProperty("opacity", mitk::FloatProperty::New(1.0) ); m_ContourHelperNode->SetProperty("line width", mitk::IntProperty::New(2) ); m_ContourHelperNode->SetProperty("scalar visibility", mitk::BoolProperty::New(false) ); m_ContourHelperNode->SetProperty( "name", mitk::StringProperty::New("surface") ); m_ContourHelperNode->SetProperty("color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); m_ContourHelperNode->SetBoolProperty("helper object", true); this->GetDataStorage()->Add(m_ContourHelperNode); } else { m_ContourHelperNode->SetData(surface); } mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkRigidRegistrationView::SetImageColor(bool redGreen) { if (!redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(m_FixedColor); } if (!redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(m_MovingColor); } if (redGreen && m_FixedNode.IsNotNull()) { m_FixedNode->SetColor(1.0f, 0.0f, 0.0f); } if (redGreen && m_MovingNode.IsNotNull()) { m_MovingNode->SetColor(0.0f, 1.0f, 0.0f); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(float opacity) { m_Opacity = opacity; if (m_MovingNode.IsNotNull()) { m_MovingNode->SetOpacity(m_Opacity); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::OpacityUpdate(int opacity) { float fValue = ((float)opacity)/100.0f; this->OpacityUpdate(fValue); } void QmitkRigidRegistrationView::ClearTransformationLists() { this->SetUndoEnabled(false); this->SetRedoEnabled(false); m_UndoGeometryList.clear(); m_UndoChildGeometryList.clear(); m_RedoGeometryList.clear(); m_RedoChildGeometryList.clear(); } void QmitkRigidRegistrationView::Translate(int* translateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D translateVec; mitk::ScalarType sliderSensitivity = 0.1; translateVec[0] = sliderSensitivity * (translateVector[0] - m_TranslateSliderPos[0]); translateVec[1] = sliderSensitivity * (translateVector[1] - m_TranslateSliderPos[1]); translateVec[2] = sliderSensitivity * (translateVector[2] - m_TranslateSliderPos[2]); m_TranslateSliderPos[0] = translateVector[0]; m_TranslateSliderPos[1] = translateVector[1]; m_TranslateSliderPos[2] = translateVector[2]; vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); translationMatrix->Identity(); double (*transMatrix)[4] = translationMatrix->Element; transMatrix[0][3] = -translateVec[0]; transMatrix[1][3] = -translateVec[1]; transMatrix[2][3] = -translateVec[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Rotate(int* rotateVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D rotateVec; rotateVec[0] = rotateVector[0] - m_RotateSliderPos[0]; rotateVec[1] = rotateVector[1] - m_RotateSliderPos[1]; rotateVec[2] = rotateVector[2] - m_RotateSliderPos[2]; m_RotateSliderPos[0] = rotateVector[0]; m_RotateSliderPos[1] = rotateVector[1]; m_RotateSliderPos[2] = rotateVector[2]; vtkMatrix4x4* rotationMatrix = vtkMatrix4x4::New(); vtkMatrix4x4* translationMatrix = vtkMatrix4x4::New(); rotationMatrix->Identity(); translationMatrix->Identity(); double (*rotMatrix)[4] = rotationMatrix->Element; double (*transMatrix)[4] = translationMatrix->Element; mitk::Point3D centerBB = m_MovingNode->GetData()->GetGeometry()->GetCenter(); transMatrix[0][3] = centerBB[0]; transMatrix[1][3] = centerBB[1]; transMatrix[2][3] = centerBB[2]; translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } double radianX = rotateVec[0] * vnl_math::pi / 180; double radianY = rotateVec[1] * vnl_math::pi / 180; double radianZ = rotateVec[2] * vnl_math::pi / 180; if ( rotateVec[0] != 0 ) { rotMatrix[1][1] = cos( radianX ); rotMatrix[1][2] = -sin( radianX ); rotMatrix[2][1] = sin( radianX ); rotMatrix[2][2] = cos( radianX ); } else if ( rotateVec[1] != 0 ) { rotMatrix[0][0] = cos( radianY ); rotMatrix[0][2] = sin( radianY ); rotMatrix[2][0] = -sin( radianY ); rotMatrix[2][2] = cos( radianY ); } else if ( rotateVec[2] != 0 ) { rotMatrix[0][0] = cos( radianZ ); rotMatrix[0][1] = -sin( radianZ ); rotMatrix[1][0] = sin( radianZ ); rotMatrix[1][1] = cos( radianZ ); } m_MovingNode->GetData()->GetGeometry()->Compose( rotationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( rotationMatrix ); childNode->GetData()->Modified(); } translationMatrix->Invert(); m_MovingNode->GetData()->GetGeometry()->Compose( translationMatrix ); for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( translationMatrix ); childNode->GetData()->Modified(); } m_MovingNode->GetData()->Modified(); m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::Scale(int* scaleVector) { if (m_MovingNode.IsNotNull()) { mitk::Vector3D scaleVec; scaleVec[0] = scaleVector[0] - m_ScaleSliderPos[0]; scaleVec[1] = scaleVector[1] - m_ScaleSliderPos[1]; scaleVec[2] = scaleVector[2] - m_ScaleSliderPos[2]; m_ScaleSliderPos[0] = scaleVector[0]; m_ScaleSliderPos[1] = scaleVector[1]; m_ScaleSliderPos[2] = scaleVector[2]; vtkMatrix4x4* scalingMatrix = vtkMatrix4x4::New(); scalingMatrix->Identity(); double (*scaleMatrix)[4] = scalingMatrix->Element; if (scaleVec[0] >= 0) { for(int i = 0; i= 0) { for(int i = 0; i= 0) { for(int i = 0; iInvert(); m_MovingNode->GetData()->GetGeometry()->Compose( scalingMatrix ); m_MovingNode->GetData()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer children = this->GetDataStorage()->GetDerivations(m_MovingNode); unsigned long size; size = children->Size(); mitk::DataNode::Pointer childNode; for (unsigned long i = 0; i < size; ++i) { childNode = children->GetElement(i); childNode->GetData()->GetGeometry()->Compose( scalingMatrix ); childNode->GetData()->Modified(); } m_RedoGeometryList.clear(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkRigidRegistrationView::AlignCenters() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { mitk::Point3D fixedPoint = m_FixedNode->GetData()->GetGeometry()->GetCenter(); mitk::Point3D movingPoint = m_MovingNode->GetData()->GetGeometry()->GetCenter(); mitk::Vector3D translateVec; translateVec = fixedPoint - movingPoint; m_Controls.m_XTransSlider->setValue((int)m_Controls.m_XTransSlider->value() + (int)translateVec[0]); m_Controls.m_YTransSlider->setValue((int)m_Controls.m_YTransSlider->value() + (int)translateVec[1]); m_Controls.m_ZTransSlider->setValue((int)m_Controls.m_ZTransSlider->value() + (int)translateVec[2]); } } void QmitkRigidRegistrationView::SetUndoEnabled( bool enable ) { m_Controls.m_UndoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::SetRedoEnabled( bool enable ) { m_Controls.m_RedoTransformation->setEnabled(enable); } void QmitkRigidRegistrationView::CheckCalculateEnabled() { if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull()) { m_Controls.m_ManualFrame->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); if ( (m_FixedDimension != m_MovingDimension && std::max(m_FixedDimension, m_MovingDimension) != 4) || m_FixedDimension < 2 /*|| m_FixedDimension > 3*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 5 && (m_FixedDimension < 2) /*|| m_FixedDimension > 3)*/) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if ((m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 4 && m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() < 13) && !(m_FixedDimension > 2)) { m_Controls.m_CalculateTransformation->setEnabled(false); } else if (m_Controls.qmitkRigidRegistrationSelector1->GetSelectedTransform() > 12 && m_FixedDimension != 2) { m_Controls.m_CalculateTransformation->setEnabled(false); } } else { m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_ManualFrame->setEnabled(false); } } void QmitkRigidRegistrationView::xTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=v; translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=v; translationParams[2]=m_Controls.m_ZTransSlider->value(); Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zTrans_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { translationParams[0]=m_Controls.m_XTransSlider->value(); translationParams[1]=m_Controls.m_YTransSlider->value(); translationParams[2]=v; Translate(translationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=v; rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=v; rotationParams[2]=m_Controls.m_ZRotSlider->value(); Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zRot_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { rotationParams[0]=m_Controls.m_XRotSlider->value(); rotationParams[1]=m_Controls.m_YRotSlider->value(); rotationParams[2]=v; Rotate(rotationParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::xScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=v; scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::yScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=v; scalingParams[2]=m_Controls.m_ZScaleSlider->value(); Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::zScale_valueChanged( int v ) { if (m_MovingNode.IsNotNull()) { scalingParams[0]=m_Controls.m_XScaleSlider->value(); scalingParams[1]=m_Controls.m_YScaleSlider->value(); scalingParams[2]=v; Scale(scalingParams); } else { MovingImageChanged(); } } void QmitkRigidRegistrationView::MovingImageChanged() { if (dynamic_cast(m_MovingNode->GetData())) { m_Controls.m_XTransSlider->setValue(0); m_Controls.m_YTransSlider->setValue(0); m_Controls.m_ZTransSlider->setValue(0); translationParams[0]=0; translationParams[1]=0; translationParams[2]=0; m_Controls.m_XRotSlider->setValue(0); m_Controls.m_YRotSlider->setValue(0); m_Controls.m_ZRotSlider->setValue(0); rotationParams[0]=0; rotationParams[1]=0; rotationParams[2]=0; m_Controls.m_XScaleSlider->setValue(0); m_Controls.m_YScaleSlider->setValue(0); m_Controls.m_ZScaleSlider->setValue(0); scalingParams[0]=0; scalingParams[1]=0; scalingParams[2]=0; m_MovingDimension = dynamic_cast(m_MovingNode->GetData())->GetDimension(); m_Controls.qmitkRigidRegistrationSelector1->SetMovingDimension(m_MovingDimension); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); this->CheckCalculateEnabled(); } } void QmitkRigidRegistrationView::Calculate() { m_Controls.qmitkRigidRegistrationSelector1->SetFixedNode(m_FixedNode); m_Controls.qmitkRigidRegistrationSelector1->SetMovingNode(m_MovingNode); if (m_FixedMaskNode.IsNotNull() && m_Controls.m_UseMaskingCB->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(m_FixedMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetFixedMaskNode(NULL); } if (m_MovingMaskNode.IsNotNull() && m_Controls.m_UseMaskingCB->isChecked()) { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(m_MovingMaskNode); } else { m_Controls.qmitkRigidRegistrationSelector1->SetMovingMaskNode(NULL); } m_Controls.frame_2->setEnabled(false); m_Controls.frame_3->setEnabled(false); m_Controls.m_CalculateTransformation->setEnabled(false); m_Controls.m_StopOptimization->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->CalculateTransformation(((QmitkSliderNavigatorWidget*)m_Controls.timeSlider)->GetPos()); m_Controls.m_StopOptimization->setEnabled(false); m_Controls.frame_2->setEnabled(true); m_Controls.frame_3->setEnabled(true); m_Controls.m_CalculateTransformation->setEnabled(true); m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(false); } void QmitkRigidRegistrationView::SetOptimizerValue( double value ) { m_Controls.m_OptimizerValueLCD->display(value); } void QmitkRigidRegistrationView::StopOptimizationClicked() { m_Controls.qmitkRigidRegistrationSelector1->StopOptimization(true); } void QmitkRigidRegistrationView::UpdateTimestep() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkRigidRegistrationView::ShowManualRegistrationFrame(bool show) { if (show) { m_Controls.m_ManualFrame->show(); } else { m_Controls.m_ManualFrame->hide(); } } void QmitkRigidRegistrationView::SetImagesVisible(berry::ISelection::ConstPointer /*selection*/) { if (this->m_CurrentSelection->Size() == 0) { // show all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(true); } } } else { // hide all images mitk::DataStorage::SetOfObjects::ConstPointer setOfObjects = this->GetDataStorage()->GetAll(); for (mitk::DataStorage::SetOfObjects::ConstIterator nodeIt = setOfObjects->Begin() ; nodeIt != setOfObjects->End(); ++nodeIt) // for each node { if ( (nodeIt->Value().IsNotNull()) && (nodeIt->Value()->GetProperty("visible")) && dynamic_cast(nodeIt->Value()->GetData())==NULL) { nodeIt->Value()->SetVisibility(false); } } } } void QmitkRigidRegistrationView::TabChanged(int index) { if (index == 0) { m_Controls.frame->hide(); } else { m_Controls.frame->show(); } } void QmitkRigidRegistrationView::SwitchImages() { mitk::DataNode::Pointer newMoving = m_FixedNode; mitk::DataNode::Pointer newFixed = m_MovingNode; this->FixedSelected(newFixed); this->MovingSelected(newMoving); if(m_ContourHelperNode.IsNotNull()) { // Update the contour ShowContour(); } if(m_Controls.m_UseMaskingCB->isChecked()) { mitk::DataNode::Pointer tempMovingMask = NULL; mitk::DataNode::Pointer tempFixedMask = NULL; if(m_FixedMaskNode.IsNotNull()) // it is initialized { tempFixedMask = m_Controls.m_FixedImageCB->GetSelectedNode(); } if(m_MovingMaskNode.IsNotNull()) // it is initialized { tempMovingMask = m_Controls.m_MovingImageCB->GetSelectedNode(); } m_Controls.m_FixedImageCB->SetSelectedNode(tempMovingMask); m_Controls.m_MovingImageCB->SetSelectedNode(tempFixedMask); } } void QmitkRigidRegistrationView::OnUseMaskingChanged( int state ) { if(state == Qt::Checked) { m_Controls.m_FixedImageCB->show(); m_Controls.m_MovingImageCB->show(); m_Controls.m_MovingMaskLB->show(); m_Controls.m_FixedMaskLB->show(); } else { m_Controls.m_FixedImageCB->hide(); m_Controls.m_MovingImageCB->hide(); m_Controls.m_MovingMaskLB->hide(); m_Controls.m_FixedMaskLB->hide(); m_FixedMaskNode = NULL; m_MovingMaskNode = NULL; } } void QmitkRigidRegistrationView::OnFixedMaskImageChanged( const mitk::DataNode* node ) { if(m_Controls.m_UseMaskingCB->isChecked()) m_FixedMaskNode = const_cast(node); else m_FixedMaskNode = NULL; } void QmitkRigidRegistrationView::OnMovingMaskImageChanged( const mitk::DataNode* node ) { if(m_Controls.m_UseMaskingCB->isChecked()) m_MovingMaskNode = const_cast(node); else m_MovingMaskNode = NULL; } diff --git a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h index c08c790b56..be401a3846 100644 --- a/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h +++ b/Plugins/org.mitk.gui.qt.registration/src/internal/QmitkRigidRegistrationView.h @@ -1,323 +1,323 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKRIGIDREGISTRATION_H #define QMITKRIGIDREGISTRATION_H #include "QmitkFunctionality.h" #include "ui_QmitkRigidRegistrationViewControls.h" #include "berryISelectionListener.h" #include "berryIStructuredSelection.h" #include // Time Slider related #include /*! \brief This functionality allows you to register 2D as well as 3D images in a rigid manner. Register means to align two images, so that they become as similar as possible. Therefore you can select from different transforms, metrics and optimizers. Registration results will directly be applied to the Moving Image. \sa QmitkFunctionality \ingroup Functionalities \ingroup RigidRegistration \author Daniel Stein */ class REGISTRATION_EXPORT QmitkRigidRegistrationView : public QmitkFunctionality { friend struct SelListenerRigidRegistration; Q_OBJECT public: static const std::string VIEW_ID; /*! \brief default constructor */ QmitkRigidRegistrationView(QObject *parent=0, const char *name=0); /*! \brief default destructor */ virtual ~QmitkRigidRegistrationView(); /*! \brief method for creating the applications main widget */ virtual void CreateQtPartControl(QWidget *parent); /*! \brief Sets the StdMultiWidget and connects it to the functionality. */ virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); /*! \brief Removes the StdMultiWidget and disconnects it from the functionality. */ virtual void StdMultiWidgetNotAvailable(); /*! \brief method for creating the connections of main and control widget */ virtual void CreateConnections(); /*! \brief Method which is called when this functionality is selected in MITK */ virtual void Activated(); /*! \brief Method which is called whenever the functionality is deselected in MITK */ virtual void Deactivated(); virtual void Visible(); virtual void Hidden(); void DataNodeHasBeenRemoved(const mitk::DataNode* node); signals: protected slots: /*! * sets the fixed Image according to TreeNodeSelector widget */ void FixedSelected(mitk::DataNode::Pointer fixedImage); /*! * sets the moving Image according to TreeNodeSelector widget */ void MovingSelected(mitk::DataNode::Pointer movingImage); /*! * checks if registration is possible */ bool CheckCalculate(); /*! * \brief Undo the last registration. */ void UndoTransformation(); /*! * \brief Redo the last registration */ void RedoTransformation(); /*! * \brief Adds a new Transformation to the undo list and enables the undo button. */ void AddNewTransformationToUndoList(); /*! * \brief Translates the moving image in x, y and z direction given by translateVector * * @param translateVector Contains the translation in x, y and z direction. */ void Translate(int* translateVector); /*! * \brief Rotates the moving image in x, y and z direction given by rotateVector * * @param rotateVector Contains the rotation around x, y and z axis. */ void Rotate(int* rotateVector); /*! * \brief Scales the moving image in x, y and z direction given by scaleVector * * @param scaleVector Contains the scaling around x, y and z axis. */ void Scale(int* scaleVector); /*! * \brief Automatically aligns the image centers. */ void AlignCenters(); /*! * \brief Stores whether the image will be shown in gray values or in red for fixed image and green for moving image * @param show if true, then images will be shown in red and green */ void ShowRedGreen(bool show); /*! * \brief Draws the contour of the fixed image according to a threshold * @param show if true, then images will be shown in red and green */ void ShowContour(); /*! * \brief Stores whether the contour of the fixed image will be shhown * @param show if true, the contour of the fixed image is shown */ void EnableContour(bool show); /*! * \brief Changes the visibility of the manual registration methods accordingly to the checkbox "Manual Registration" in GUI * @param show if true, then manual registration methods will be shown */ void ShowManualRegistrationFrame(bool show); /*! * \brief Sets the selected opacity for moving image * @param opacity the selected opacity */ void OpacityUpdate(float opacity); /*! \brief Sets the selected opacity for moving image @param opacity the selected opacity */ void OpacityUpdate(int opacity); /*! * \brief Sets the images to grayvalues or fixed image to red and moving image to green * @param redGreen if true, then images will be shown in red and green */ void SetImageColor(bool redGreen); /*! * \brief Clears the undo and redo lists and sets the undo and redo buttons to disabled. */ void ClearTransformationLists(); void SetUndoEnabled( bool enable ); void SetRedoEnabled( bool enable ); void CheckCalculateEnabled(); void xTrans_valueChanged( int v ); void yTrans_valueChanged( int v ); void zTrans_valueChanged( int v ); void xRot_valueChanged( int v ); void yRot_valueChanged( int v ); void zRot_valueChanged( int v ); void xScale_valueChanged( int v ); void yScale_valueChanged( int v ); void zScale_valueChanged( int v ); void MovingImageChanged(); /*! * \brief Starts the registration process. */ void Calculate(); void SetOptimizerValue( double value ); void StopOptimizationClicked(); void UpdateTimestep(); void SetImagesVisible(berry::ISelection::ConstPointer /*selection*/); //void CheckForMaskImages(); //void UseFixedMaskImageChecked(bool checked); //void UseMovingMaskImageChecked(bool checked); void TabChanged(int index); void SwitchImages(); /*! * indicates if the masking option shall be used. */ void OnUseMaskingChanged(int state); /*! * method called if the fixed mask image selector changed. */ void OnFixedMaskImageChanged(const mitk::DataNode* node); /*! * method called if the moving mask image selector changed. */ void OnMovingMaskImageChanged(const mitk::DataNode* node); protected: - berry::ISelectionListener::Pointer m_SelListener; + QScopedPointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; /*! * default main widget containing 4 windows showing 3 * orthogonal slices of the volume and a 3d render window */ QmitkStdMultiWidget * m_MultiWidget; /*! * control widget to make all changes for Deformable registration */ Ui::QmitkRigidRegistrationViewControls m_Controls; mitk::DataNode::Pointer m_MovingNode; mitk::DataNode::Pointer m_MovingMaskNode; mitk::DataNode::Pointer m_FixedNode; mitk::DataNode::Pointer m_FixedMaskNode; // A node to store the contour of the fixed image in mitk::DataNode::Pointer m_ContourHelperNode; typedef std::map GeometryMapType; typedef std::list< GeometryMapType > GeometryMapListType; typedef std::list GeometryListType; GeometryListType m_UndoGeometryList; GeometryMapListType m_UndoChildGeometryList; GeometryListType m_RedoGeometryList; GeometryMapListType m_RedoChildGeometryList; bool m_ShowRedGreen; float m_Opacity; float m_OriginalOpacity; bool m_Deactivated; int m_FixedDimension; int m_MovingDimension; int * translationParams; int * rotationParams; int * scalingParams; mitk::Color m_FixedColor; mitk::Color m_MovingColor; int m_TranslateSliderPos[3]; int m_RotateSliderPos[3]; int m_ScaleSliderPos[3]; QmitkStepperAdapter* m_TimeStepperAdapter; }; #endif //QMITKRigidREGISTRATION_H diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp index 1fb825e6c5..359c86ae78 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.cpp @@ -1,195 +1,193 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkSegmentationPreferencePage.h" #include #include #include #include #include #include #include #include #include #include QmitkSegmentationPreferencePage::QmitkSegmentationPreferencePage() : m_MainControl(0) , m_Initializing(false) { } QmitkSegmentationPreferencePage::~QmitkSegmentationPreferencePage() { } void QmitkSegmentationPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkSegmentationPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; - berry::IPreferencesService::Pointer prefService - = berry::Platform::GetServiceRegistry() - .GetServiceById(berry::IPreferencesService::ID); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_SegmentationPreferencesNode = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); m_MainControl = new QWidget(parent); QFormLayout *formLayout = new QFormLayout; formLayout->setHorizontalSpacing(8); formLayout->setVerticalSpacing(24); m_SlimViewCheckBox = new QCheckBox("Hide tool button texts and increase icon size", m_MainControl); formLayout->addRow("Slim view", m_SlimViewCheckBox); QVBoxLayout* displayOptionsLayout = new QVBoxLayout; m_RadioOutline = new QRadioButton( "Draw as outline", m_MainControl); displayOptionsLayout->addWidget( m_RadioOutline ); m_RadioOverlay = new QRadioButton( "Draw as transparent overlay", m_MainControl); displayOptionsLayout->addWidget( m_RadioOverlay ); formLayout->addRow( "2D display", displayOptionsLayout ); m_VolumeRenderingCheckBox = new QCheckBox( "Show as volume rendering", m_MainControl ); formLayout->addRow( "3D display", m_VolumeRenderingCheckBox ); connect( m_VolumeRenderingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnVolumeRenderingCheckboxChecked(int)) ); QFormLayout* surfaceLayout = new QFormLayout; surfaceLayout->setSpacing(8); m_SmoothingCheckBox = new QCheckBox("Use image spacing as smoothing value hint", m_MainControl); surfaceLayout->addRow(m_SmoothingCheckBox); connect(m_SmoothingCheckBox, SIGNAL(stateChanged(int)), this, SLOT(OnSmoothingCheckboxChecked(int))); m_SmoothingSpinBox = new QDoubleSpinBox(m_MainControl); m_SmoothingSpinBox->setMinimum(0.0); m_SmoothingSpinBox->setSingleStep(0.5); m_SmoothingSpinBox->setValue(1.0); m_SmoothingSpinBox->setToolTip("The Smoothing value is used as variance for a gaussian blur."); surfaceLayout->addRow("Smoothing value (mm)", m_SmoothingSpinBox); m_DecimationSpinBox = new QDoubleSpinBox(m_MainControl); m_DecimationSpinBox->setMinimum(0.0); m_DecimationSpinBox->setMaximum(0.99); m_DecimationSpinBox->setSingleStep(0.1); m_DecimationSpinBox->setValue(0.5); m_DecimationSpinBox->setToolTip("Valid range is [0, 1). High values increase decimation, especially when very close to 1. A value of 0 disables decimation."); surfaceLayout->addRow("Decimation rate", m_DecimationSpinBox); m_ClosingSpinBox = new QDoubleSpinBox(m_MainControl); m_ClosingSpinBox->setMinimum(0.0); m_ClosingSpinBox->setMaximum(1.0); m_ClosingSpinBox->setSingleStep(0.1); m_ClosingSpinBox->setValue(0.0); m_ClosingSpinBox->setToolTip("Valid range is [0, 1]. Higher values increase closing. A value of 0 disables closing."); surfaceLayout->addRow("Closing Ratio", m_ClosingSpinBox); m_SelectionModeCheckBox = new QCheckBox("Enable auto-selection mode", m_MainControl); m_SelectionModeCheckBox->setToolTip("If checked the segmentation plugin ensures that only one segmentation and the according greyvalue image are visible at one time."); formLayout->addRow("Data node selection mode",m_SelectionModeCheckBox); formLayout->addRow("Smoothed surface creation", surfaceLayout); m_MainControl->setLayout(formLayout); this->Update(); m_Initializing = false; } QWidget* QmitkSegmentationPreferencePage::GetQtControl() const { return m_MainControl; } bool QmitkSegmentationPreferencePage::PerformOk() { m_SegmentationPreferencesNode->PutBool("slim view", m_SlimViewCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("draw outline", m_RadioOutline->isChecked()); m_SegmentationPreferencesNode->PutBool("volume rendering", m_VolumeRenderingCheckBox->isChecked()); m_SegmentationPreferencesNode->PutBool("smoothing hint", m_SmoothingCheckBox->isChecked()); m_SegmentationPreferencesNode->PutDouble("smoothing value", m_SmoothingSpinBox->value()); m_SegmentationPreferencesNode->PutDouble("decimation rate", m_DecimationSpinBox->value()); m_SegmentationPreferencesNode->PutDouble("closing ratio", m_ClosingSpinBox->value()); m_SegmentationPreferencesNode->PutBool("auto selection", m_SelectionModeCheckBox->isChecked()); return true; } void QmitkSegmentationPreferencePage::PerformCancel() { } void QmitkSegmentationPreferencePage::Update() { //m_EnableSingleEditing->setChecked(m_SegmentationPreferencesNode->GetBool("Single click property editing", true)); m_SlimViewCheckBox->setChecked(m_SegmentationPreferencesNode->GetBool("slim view", false)); if (m_SegmentationPreferencesNode->GetBool("draw outline", true) ) { m_RadioOutline->setChecked( true ); } else { m_RadioOverlay->setChecked( true ); } m_VolumeRenderingCheckBox->setChecked( m_SegmentationPreferencesNode->GetBool("volume rendering", false) ); if (m_SegmentationPreferencesNode->GetBool("smoothing hint", true)) { m_SmoothingCheckBox->setChecked(true); m_SmoothingSpinBox->setDisabled(true); } else { m_SmoothingCheckBox->setChecked(false); m_SmoothingSpinBox->setEnabled(true); } m_SelectionModeCheckBox->setChecked( m_SegmentationPreferencesNode->GetBool("auto selection", true) ); m_SmoothingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("smoothing value", 1.0)); m_DecimationSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("decimation rate", 0.5)); m_ClosingSpinBox->setValue(m_SegmentationPreferencesNode->GetDouble("closing ratio", 0.0)); } void QmitkSegmentationPreferencePage::OnVolumeRenderingCheckboxChecked(int state) { if (m_Initializing) return; if ( state != Qt::Unchecked ) { QMessageBox::information(NULL, "Memory warning", "Turning on volume rendering of segmentations will make the application more memory intensive (and potentially prone to crashes).\n\n" "If you encounter out-of-memory problems, try turning off volume rendering again."); } } void QmitkSegmentationPreferencePage::OnSmoothingCheckboxChecked(int state) { if (state != Qt::Unchecked) m_SmoothingSpinBox->setDisabled(true); else m_SmoothingSpinBox->setEnabled(true); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/Common/QmitkDataSelectionWidget.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/Common/QmitkDataSelectionWidget.cpp index 231887ec1c..e9ae10af70 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/Common/QmitkDataSelectionWidget.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/Common/QmitkDataSelectionWidget.cpp @@ -1,165 +1,168 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDataSelectionWidget.h" -#include +#include "../mitkPluginActivator.h" + +#include + #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static mitk::NodePredicateBase::Pointer CreatePredicate(QmitkDataSelectionWidget::Predicate predicate) { switch(predicate) { case QmitkDataSelectionWidget::ImagePredicate: return mitk::NodePredicateAnd::New( mitk::TNodePredicateDataType::New(), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true))), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer(); case QmitkDataSelectionWidget::SegmentationPredicate: return mitk::NodePredicateAnd::New( mitk::TNodePredicateDataType::New(), mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer(); case QmitkDataSelectionWidget::SurfacePredicate: return mitk::NodePredicateAnd::New( mitk::TNodePredicateDataType::New(), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer(); case QmitkDataSelectionWidget::ImageAndSegmentationPredicate: return mitk::NodePredicateAnd::New( mitk::TNodePredicateDataType::New(), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer(); case QmitkDataSelectionWidget::ContourModelPredicate: return mitk::NodePredicateAnd::New( mitk::NodePredicateOr::New( mitk::TNodePredicateDataType::New(), mitk::TNodePredicateDataType::New()), mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer(); default: assert(false && "Unknown predefined predicate!"); return NULL; } } QmitkDataSelectionWidget::QmitkDataSelectionWidget(QWidget* parent) : QWidget(parent) { m_Controls.setupUi(this); m_Controls.helpLabel->hide(); } QmitkDataSelectionWidget::~QmitkDataSelectionWidget() { } unsigned int QmitkDataSelectionWidget::AddDataStorageComboBox(QmitkDataSelectionWidget::Predicate predicate) { return this->AddDataStorageComboBox("", predicate); } unsigned int QmitkDataSelectionWidget::AddDataStorageComboBox(mitk::NodePredicateBase* predicate) { return this->AddDataStorageComboBox("", predicate); } unsigned int QmitkDataSelectionWidget::AddDataStorageComboBox(const QString &labelText, QmitkDataSelectionWidget::Predicate predicate) { return this->AddDataStorageComboBox(labelText, CreatePredicate(predicate)); } unsigned int QmitkDataSelectionWidget::AddDataStorageComboBox(const QString &labelText, mitk::NodePredicateBase* predicate) { int row = m_Controls.gridLayout->rowCount(); if (!labelText.isEmpty()) { QLabel* label = new QLabel(labelText, m_Controls.dataSelectionWidget); label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); m_Controls.gridLayout->addWidget(label, row, 0); } QmitkDataStorageComboBox* comboBox = new QmitkDataStorageComboBox(this->GetDataStorage(), predicate, m_Controls.dataSelectionWidget); connect(comboBox, SIGNAL(OnSelectionChanged(const mitk::DataNode *)), this, SLOT(OnSelectionChanged(const mitk::DataNode *))); m_Controls.gridLayout->addWidget(comboBox, row, 1); m_DataStorageComboBoxes.push_back(comboBox); return static_cast(m_DataStorageComboBoxes.size() - 1); } mitk::DataStorage::Pointer QmitkDataSelectionWidget::GetDataStorage() const { - mitk::IDataStorageService::Pointer service = - berry::Platform::GetServiceRegistry().GetServiceById(mitk::IDataStorageService::ID); + mitk::IDataStorageService* service = + mitk::PluginActivator::getDefault()->GetWorkbench()->GetService(); - assert(service.IsNotNull()); + assert(service); return service->GetDefaultDataStorage()->GetDataStorage(); } mitk::DataNode::Pointer QmitkDataSelectionWidget::GetSelection(unsigned int index) { assert(index < m_DataStorageComboBoxes.size()); return m_DataStorageComboBoxes[index]->GetSelectedNode(); } void QmitkDataSelectionWidget::SetPredicate(unsigned int index, Predicate predicate) { this->SetPredicate(index, CreatePredicate(predicate)); } void QmitkDataSelectionWidget::SetPredicate(unsigned int index, mitk::NodePredicateBase* predicate) { assert(index < m_DataStorageComboBoxes.size()); m_DataStorageComboBoxes[index]->SetPredicate(predicate); } void QmitkDataSelectionWidget::SetHelpText(const QString& text) { if (!text.isEmpty()) { m_Controls.helpLabel->setText(text); if (!m_Controls.helpLabel->isVisible()) m_Controls.helpLabel->show(); } else { m_Controls.helpLabel->hide(); } } void QmitkDataSelectionWidget::OnSelectionChanged(const mitk::DataNode* selection) { std::vector::iterator it = std::find(m_DataStorageComboBoxes.begin(), m_DataStorageComboBoxes.end(), sender()); assert(it != m_DataStorageComboBoxes.end()); emit SelectionChanged(std::distance(m_DataStorageComboBoxes.begin(), it), selection); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp index 26ee3aa451..3b651a16f6 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkCreatePolygonModelAction.cpp @@ -1,139 +1,140 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkCreatePolygonModelAction.h" // MITK #include #include #include #include #include #include #include // Blueberry #include -#include +#include +#include #include using namespace berry; using namespace mitk; using namespace std; QmitkCreatePolygonModelAction::QmitkCreatePolygonModelAction() { } QmitkCreatePolygonModelAction::~QmitkCreatePolygonModelAction() { } void QmitkCreatePolygonModelAction::Run(const QList &selectedNodes) { DataNode::Pointer selectedNode = selectedNodes[0]; Image::Pointer image = dynamic_cast(selectedNode->GetData()); if (image.IsNull()) { return; } try { // Get preference properties for smoothing and decimation - IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); + IPreferencesService* prefService = Platform::GetPreferencesService(); IPreferences::Pointer segPref = prefService->GetSystemPreferences()->Node("/org.mitk.views.segmentation"); bool smoothingHint = segPref->GetBool("smoothing hint", true); ScalarType smoothing = segPref->GetDouble("smoothing value", 1.0); ScalarType decimation = segPref->GetDouble("decimation rate", 0.5); if (smoothingHint) { smoothing = 0.0; Vector3D spacing = image->GetGeometry()->GetSpacing(); for (Vector3D::Iterator iter = spacing.Begin(); iter != spacing.End(); ++iter) smoothing = max(smoothing, *iter); } ShowSegmentationAsSurface::Pointer surfaceFilter = ShowSegmentationAsSurface::New(); // Activate callback functions itk::SimpleMemberCommand::Pointer successCommand = itk::SimpleMemberCommand::New(); successCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ResultAvailable(), successCommand); itk::SimpleMemberCommand::Pointer errorCommand = itk::SimpleMemberCommand::New(); errorCommand->SetCallbackFunction(this, &QmitkCreatePolygonModelAction::OnSurfaceCalculationDone); surfaceFilter->AddObserver(ProcessingError(), errorCommand); // set filter parameter surfaceFilter->SetDataStorage(*m_DataStorage); surfaceFilter->SetPointerParameter("Input", image); surfaceFilter->SetPointerParameter("Group node", selectedNode); surfaceFilter->SetParameter("Show result", true); surfaceFilter->SetParameter("Sync visibility", false); surfaceFilter->SetParameter("Median kernel size", 3u); surfaceFilter->SetParameter("Decimate mesh", m_IsDecimated); surfaceFilter->SetParameter("Decimation rate", (float) decimation); if (m_IsSmoothed) { surfaceFilter->SetParameter("Apply median", true); surfaceFilter->SetParameter("Smooth", true); surfaceFilter->SetParameter("Gaussian SD", sqrtf(smoothing)); // use sqrt to account for setting of variance in preferences StatusBar::GetInstance()->DisplayText("Smoothed surface creation started in background..."); } else { surfaceFilter->SetParameter("Apply median", false); surfaceFilter->SetParameter("Smooth", false); StatusBar::GetInstance()->DisplayText("Surface creation started in background..."); } surfaceFilter->StartAlgorithm(); } catch(...) { MITK_ERROR << "Surface creation failed!"; } } void QmitkCreatePolygonModelAction::OnSurfaceCalculationDone() { StatusBar::GetInstance()->Clear(); } void QmitkCreatePolygonModelAction::SetDataStorage(DataStorage *dataStorage) { m_DataStorage = dataStorage; } void QmitkCreatePolygonModelAction::SetSmoothed(bool smoothed) { m_IsSmoothed = smoothed; } void QmitkCreatePolygonModelAction::SetDecimated(bool decimated) { m_IsDecimated = decimated; } void QmitkCreatePolygonModelAction::SetFunctionality(QtViewPart *) { -} \ No newline at end of file +} diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp index e42389f50c..7740c91d02 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1248 +1,1248 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkProperties.h" #include "mitkSegTool2D.h" #include "mitkStatusBar.h" #include "QmitkStdMultiWidget.h" #include "QmitkNewSegmentationDialog.h" #include #include #include "QmitkSegmentationView.h" #include "QmitkSegmentationOrganNamesHandling.cpp" #include #include "mitkVtkResliceInterpolationProperty.h" #include "mitkApplicationCursor.h" #include "mitkSegmentationObjectFactory.h" #include "mitkPluginActivator.h" #include "usModuleResource.h" #include "usModuleResourceStream.h" //micro service to get the ToolManager instance #include "mitkToolManagerProvider.h" const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; // public methods QmitkSegmentationView::QmitkSegmentationView() :m_Parent(NULL) ,m_Controls(NULL) ,m_MultiWidget(NULL) ,m_DataSelectionChanged(false) ,m_MouseCursorSet(false) { mitk::NodePredicateDataType::Pointer isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isQbi = mitk::NodePredicateDataType::New("QBallImage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isQbi); m_IsOfTypeImagePredicate = mitk::NodePredicateOr::New(isDiffusionImage, mitk::TNodePredicateDataType::New()); m_IsBinaryPredicate = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); m_IsNotBinaryPredicate = mitk::NodePredicateNot::New( m_IsBinaryPredicate ); m_IsNotABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsNotBinaryPredicate ); m_IsABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsBinaryPredicate); } QmitkSegmentationView::~QmitkSegmentationView() { delete m_Controls; } void QmitkSegmentationView::NewNodesGenerated() { MITK_WARN<<"Use of deprecated function: NewNodesGenerated!! This function is empty and will be removed in the next time!"; } void QmitkSegmentationView::NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType* nodes) { if (!nodes) return; mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); if (!toolManager) return; for (mitk::ToolManager::DataVectorType::iterator iter = nodes->begin(); iter != nodes->end(); ++iter) { this->FireNodeSelected( *iter ); // only last iteration meaningful, multiple generated objects are not taken into account here } } void QmitkSegmentationView::Visible() { if (m_DataSelectionChanged) { this->OnSelectionChanged(this->GetDataManagerSelection()); } } void QmitkSegmentationView::Activated() { // should be moved to ::BecomesVisible() or similar if( m_Controls ) { m_Controls->m_ManualToolSelectionBox2D->setEnabled( true ); m_Controls->m_ManualToolSelectionBox3D->setEnabled( true ); // m_Controls->m_OrganToolSelectionBox->setEnabled( true ); // m_Controls->m_LesionToolSelectionBox->setEnabled( true ); // m_Controls->m_SlicesInterpolator->Enable3DInterpolation( m_Controls->widgetStack->currentWidget() == m_Controls->pageManual ); mitk::DataStorage::SetOfObjects::ConstPointer segmentations = this->GetDefaultDataStorage()->GetSubset( m_IsABinaryImagePredicate ); mitk::DataStorage::SetOfObjects::ConstPointer image = this->GetDefaultDataStorage()->GetSubset( m_IsNotABinaryImagePredicate ); if (!image->empty()) { OnSelectionChanged(*image->begin()); } for ( mitk::DataStorage::SetOfObjects::const_iterator iter = segmentations->begin(); iter != segmentations->end(); ++iter) { mitk::DataNode* node = *iter; itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( node, node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( node, node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); } } itk::SimpleMemberCommand::Pointer command3 = itk::SimpleMemberCommand::New(); command3->SetCallbackFunction( this, &QmitkSegmentationView::RenderingManagerReinitialized ); m_RenderingManagerObserverTag = mitk::RenderingManager::GetInstance()->AddObserver( mitk::RenderingManagerViewsInitializedEvent(), command3 ); this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), m_Controls->segImageSelector->GetSelectedNode()); } void QmitkSegmentationView::Deactivated() { if( m_Controls ) { this->SetToolSelectionBoxesEnabled( false ); //deactivate all tools mitk::ToolManagerProvider::GetInstance()->GetToolManager()->ActivateTool(-1); //Removing all observers for ( NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("visible")->RemoveObserver( (*dataIter).second ); } m_WorkingDataObserverTags.clear(); for ( NodeTagMapType::iterator dataIter = m_BinaryPropertyObserverTags.begin(); dataIter != m_BinaryPropertyObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("binary")->RemoveObserver( (*dataIter).second ); } m_BinaryPropertyObserverTags.clear(); mitk::RenderingManager::GetInstance()->RemoveObserver(m_RenderingManagerObserverTag); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); service->RemoveAllPlanePositions(); context->ungetService(ppmRef); this->SetToolManagerSelection(0,0); } } void QmitkSegmentationView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { SetMultiWidget(&stdMultiWidget); } void QmitkSegmentationView::StdMultiWidgetNotAvailable() { SetMultiWidget(NULL); } void QmitkSegmentationView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { SetMultiWidget(NULL); } void QmitkSegmentationView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { // save the current multiwidget as the working widget m_MultiWidget = multiWidget; if (m_Parent) { m_Parent->setEnabled(m_MultiWidget); } // tell the interpolation about toolmanager and multiwidget (and data storage) if (m_Controls && m_MultiWidget) { mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_Controls->m_SlicesInterpolator->SetDataStorage( this->GetDefaultDataStorage()); QList controllers; controllers.push_back(m_MultiWidget->GetRenderWindow1()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow2()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow3()->GetSliceNavigationController()); m_Controls->m_SlicesInterpolator->Initialize( toolManager, controllers ); } } void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { if (m_Controls != NULL) { bool slimView = prefs->GetBool("slim view", false); m_Controls->m_ManualToolSelectionBox2D->SetShowNames(!slimView); m_Controls->m_ManualToolSelectionBox3D->SetShowNames(!slimView); } m_AutoSelectionEnabled = prefs->GetBool("auto selection", false); this->ForceDisplayPreferencesUponAllImages(); } void QmitkSegmentationView::CreateNewSegmentation() { mitk::DataNode::Pointer node = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { if (image->GetDimension()>1) { // ask about the name and organ type of the new segmentation QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( m_Parent ); // needs a QWidget as parent, "this" is not QWidget - QString storedList = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); + QString storedList = this->GetPreferences()->Get("Organ-Color-List",""); QStringList organColors; if (storedList.isEmpty()) { organColors = GetDefaultOrganColorString(); } else { /* a couple of examples of how organ names are stored: a simple item is built up like 'name#AABBCC' where #AABBCC is the hexadecimal notation of a color as known from HTML items are stored separated by ';' this makes it necessary to escape occurrences of ';' in name. otherwise the string "hugo;ypsilon#AABBCC;eugen#AABBCC" could not be parsed as two organs but we would get "hugo" and "ypsilon#AABBCC" and "eugen#AABBCC" so the organ name "hugo;ypsilon" is stored as "hugo\;ypsilon" and must be unescaped after loading the following lines could be one split with Perl's negative lookbehind */ // recover string list from BlueBerry view's preferences - QString storedString = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); + QString storedString = this->GetPreferences()->Get("Organ-Color-List",""); MITK_DEBUG << "storedString: " << storedString.toStdString(); // match a string consisting of any number of repetitions of either "anything but ;" or "\;". This matches everything until the next unescaped ';' QRegExp onePart("(?:[^;]|\\\\;)*"); MITK_DEBUG << "matching " << onePart.pattern().toStdString(); int count = 0; int pos = 0; while( (pos = onePart.indexIn( storedString, pos )) != -1 ) { ++count; int length = onePart.matchedLength(); if (length == 0) break; QString matchedString = storedString.mid(pos, length); MITK_DEBUG << " Captured length " << length << ": " << matchedString.toStdString(); pos += length + 1; // skip separating ';' // unescape possible occurrences of '\;' in the string matchedString.replace("\\;", ";"); // add matched string part to output list organColors << matchedString; } MITK_DEBUG << "Captured " << count << " organ name/colors"; } dialog->SetSuggestionList( organColors ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; // user clicked cancel or pressed Esc or something similar // ask the user about an organ type and name, add this information to the image's (!) propertylist // create a new image of the same dimensions and smallest possible pixel type mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); mitk::Tool* firstTool = toolManager->GetToolById(0); if (firstTool) { try { std::string newNodeName = dialog->GetSegmentationName().toStdString(); if(newNodeName.empty()) newNodeName = "no_name"; mitk::DataNode::Pointer emptySegmentation = firstTool->CreateEmptySegmentationNode( image, newNodeName, dialog->GetColor() ); // initialize showVolume to false to prevent recalculating the volume while working on the segmentation emptySegmentation->SetProperty( "showVolume", mitk::BoolProperty::New( false ) ); if (!emptySegmentation) return; // could be aborted by user UpdateOrganList( organColors, dialog->GetSegmentationName(), dialog->GetColor() ); /* escape ';' here (replace by '\;'), see longer comment above */ - std::string stringForStorage = organColors.replaceInStrings(";","\\;").join(";").toStdString(); + QString stringForStorage = organColors.replaceInStrings(";","\\;").join(";"); MITK_DEBUG << "Will store: " << stringForStorage; - this->GetPreferences()->PutByteArray("Organ-Color-List", stringForStorage ); + this->GetPreferences()->Put("Organ-Color-List", stringForStorage); this->GetPreferences()->Flush(); if(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0)) { mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0)->SetSelected(false); } emptySegmentation->SetSelected(true); this->GetDefaultDataStorage()->Add( emptySegmentation, node ); // add as a child, because the segmentation "derives" from the original this->ApplyDisplayOptions( emptySegmentation ); this->FireNodeSelected( emptySegmentation ); this->OnSelectionChanged( emptySegmentation ); m_Controls->segImageSelector->SetSelectedNode(emptySegmentation); mitk::RenderingManager::GetInstance()->InitializeViews(emptySegmentation->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); } catch (std::bad_alloc) { QMessageBox::warning(NULL,"Create new segmentation","Could not allocate memory for new segmentation"); } } } else { QMessageBox::information(NULL,"Segmentation","Segmentation is currently not supported for 2D images"); } } } else { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a patient image is selected..."; } } void QmitkSegmentationView::OnWorkingNodeVisibilityChanged() { mitk::DataNode* selectedNode = m_Controls->segImageSelector->GetSelectedNode(); if ( !selectedNode ) { this->SetToolSelectionBoxesEnabled(false); return; } bool selectedNodeIsVisible = selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); if (!selectedNodeIsVisible) { this->SetToolSelectionBoxesEnabled(false); this->UpdateWarningLabel("The selected segmentation is currently not visible!"); } else { this->SetToolSelectionBoxesEnabled(true); this->UpdateWarningLabel(""); } } void QmitkSegmentationView::OnBinaryPropertyChanged() { mitk::DataStorage::SetOfObjects::ConstPointer patImages = m_Controls->patImageSelector->GetNodes(); bool isBinary(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = patImages->Begin(); it != patImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(isBinary) { m_Controls->patImageSelector->RemoveNode(node); m_Controls->segImageSelector->AddNode(node); this->SetToolManagerSelection(NULL,NULL); return; } } mitk::DataStorage::SetOfObjects::ConstPointer segImages = m_Controls->segImageSelector->GetNodes(); isBinary = true; for (mitk::DataStorage::SetOfObjects::ConstIterator it = segImages->Begin(); it != segImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(!isBinary) { m_Controls->segImageSelector->RemoveNode(node); m_Controls->patImageSelector->AddNode(node); if (mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0) == node) mitk::ToolManagerProvider::GetInstance()->GetToolManager()->SetWorkingData(NULL); return; } } } void QmitkSegmentationView::NodeAdded(const mitk::DataNode *node) { bool isBinary (false); bool isHelperObject (false); node->GetBoolProperty("binary", isBinary); node->GetBoolProperty("helper object", isHelperObject); if (m_AutoSelectionEnabled) { if (!isBinary && dynamic_cast(node->GetData())) { FireNodeSelected(const_cast(node)); } } if (isBinary && !isHelperObject) { itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( const_cast(node), node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( const_cast(node), node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); this->ApplyDisplayOptions( const_cast(node) ); m_Controls->segImageSelector->setCurrentIndex( m_Controls->segImageSelector->Find(node) ); } } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { bool isSeg(false); bool isHelperObject(false); node->GetBoolProperty("helper object", isHelperObject); node->GetBoolProperty("binary", isSeg); mitk::Image* image = dynamic_cast(node->GetData()); if(isSeg && !isHelperObject && image) { //First of all remove all possible contour markers of the segmentation mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = this->GetDataStorage()->GetDerivations(node, mitk::NodePredicateProperty::New("isContourMarker" , mitk::BoolProperty::New(true))); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; service->RemovePlanePosition(id); this->GetDataStorage()->Remove(it->Value()); } context->ungetService(ppmRef); service = NULL; if ((mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0) == node) && m_Controls->patImageSelector->GetSelectedNode().IsNotNull()) { this->SetToolManagerSelection(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0), NULL); this->UpdateWarningLabel("Select or create a segmentation"); } mitk::SurfaceInterpolationController::GetInstance()->RemoveSegmentationFromContourList(image); } mitk::DataNode* tempNode = const_cast(node); //Since the binary property could be changed during runtime by the user if (image && !isHelperObject) { node->GetProperty("visible")->RemoveObserver( m_WorkingDataObserverTags[tempNode] ); m_WorkingDataObserverTags.erase(tempNode); node->GetProperty("binary")->RemoveObserver( m_BinaryPropertyObserverTags[tempNode] ); m_BinaryPropertyObserverTags.erase(tempNode); } if((mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0) == node)) { //as we don't know which node was actually removed e.g. our reference node, disable 'New Segmentation' button. //consider the case that there is no more image in the datastorage this->SetToolManagerSelection(NULL, NULL); this->SetToolSelectionBoxesEnabled( false ); } } //void QmitkSegmentationView::CreateSegmentationFromSurface() //{ // mitk::DataNode::Pointer surfaceNode = // m_Controls->MaskSurfaces->GetSelectedNode(); // mitk::Surface::Pointer surface(0); // if(surfaceNode.IsNotNull()) // surface = dynamic_cast ( surfaceNode->GetData() ); // if(surface.IsNull()) // { // this->HandleException( "No surface selected.", m_Parent, true); // return; // } // mitk::DataNode::Pointer imageNode // = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); // mitk::Image::Pointer image(0); // if (imageNode.IsNotNull()) // image = dynamic_cast( imageNode->GetData() ); // if(image.IsNull()) // { // this->HandleException( "No image selected.", m_Parent, true); // return; // } // mitk::SurfaceToImageFilter::Pointer s2iFilter // = mitk::SurfaceToImageFilter::New(); // s2iFilter->MakeOutputBinaryOn(); // s2iFilter->SetInput(surface); // s2iFilter->SetImage(image); // s2iFilter->Update(); // mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); // std::string nameOfResultImage = imageNode->GetName(); // nameOfResultImage.append(surfaceNode->GetName()); // resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); // resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); // resultNode->SetData( s2iFilter->GetOutput() ); // this->GetDataStorage()->Add(resultNode, imageNode); //} //void QmitkSegmentationView::ToolboxStackPageChanged(int id) //{ // // interpolation only with manual tools visible // m_Controls->m_SlicesInterpolator->EnableInterpolation( id == 0 ); // if( id == 0 ) // { // mitk::DataNode::Pointer workingData = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0); // if( workingData.IsNotNull() ) // { // m_Controls->segImageSelector->setCurrentIndex( m_Controls->segImageSelector->Find(workingData) ); // } // } // // this is just a workaround, should be removed when all tools support 3D+t // if (id==2) // lesions // { // mitk::DataNode::Pointer node = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); // if (node.IsNotNull()) // { // mitk::Image::Pointer image = dynamic_cast( node->GetData() ); // if (image.IsNotNull()) // { // if (image->GetDimension()>3) // { // m_Controls->widgetStack->setCurrentIndex(0); // QMessageBox::information(NULL,"Segmentation","Lesion segmentation is currently not supported for 4D images"); // } // } // } // } //} // protected void QmitkSegmentationView::OnPatientComboBoxSelectionChanged( const mitk::DataNode* node ) { //mitk::DataNode* selectedNode = const_cast(node); if( node != NULL ) { this->UpdateWarningLabel(""); mitk::DataNode* segNode = m_Controls->segImageSelector->GetSelectedNode(); if (segNode) { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( segNode, m_IsNotABinaryImagePredicate ); bool isSourceNode(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possibleParents->Begin(); it != possibleParents->End(); it++) { if (it.Value() == node) isSourceNode = true; } if ( !isSourceNode && (!this->CheckForSameGeometry(segNode, node) || possibleParents->Size() > 0 )) { this->SetToolManagerSelection(node, NULL); this->SetToolSelectionBoxesEnabled( false ); this->UpdateWarningLabel("The selected patient image does not match with the selected segmentation!"); } else if ((!isSourceNode && this->CheckForSameGeometry(segNode, node)) || isSourceNode ) { this->SetToolManagerSelection(node, segNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are //loaded separately int layer(10); node->GetIntProperty("layer", layer); layer++; segNode->SetProperty("layer", mitk::IntProperty::New(layer)); //this->UpdateWarningLabel(""); RenderingManagerReinitialized(); } } else { this->SetToolManagerSelection(node, NULL); this->SetToolSelectionBoxesEnabled( false ); this->UpdateWarningLabel("Select or create a segmentation"); } } else { this->UpdateWarningLabel("Please load an image!"); this->SetToolSelectionBoxesEnabled( false ); } } void QmitkSegmentationView::OnSegmentationComboBoxSelectionChanged(const mitk::DataNode *node) { if (node == NULL) { this->UpdateWarningLabel("Select or create a segmentation"); this->SetToolSelectionBoxesEnabled( false ); return; } mitk::DataNode* refNode = m_Controls->patImageSelector->GetSelectedNode(); RenderingManagerReinitialized(); if ( m_Controls->lblSegmentationWarnings->isVisible()) // "RenderingManagerReinitialized()" caused a warning. we do not need to go any further return; if (m_AutoSelectionEnabled) { this->OnSelectionChanged(const_cast(node)); } else { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( node, m_IsNotABinaryImagePredicate ); if ( possibleParents->Size() == 1 ) { mitk::DataNode* parentNode = possibleParents->ElementAt(0); if (parentNode != refNode) { this->UpdateWarningLabel("The selected segmentation does not match with the selected patient image!"); this->SetToolSelectionBoxesEnabled( false ); this->SetToolManagerSelection(NULL, node); } else { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } } else if (refNode && this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } else if (!refNode || !this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel("Please select or load the according patient image!"); } } if (!node->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) { this->UpdateWarningLabel("The selected segmentation is currently not visible!"); this->SetToolSelectionBoxesEnabled( false ); } } void QmitkSegmentationView::OnShowMarkerNodes (bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetTools().size(); for(unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetToolById(i)); if (manualSegmentationTool) { if(state == true) { manualSegmentationTool->SetShowMarkerNodes( true ); } else { manualSegmentationTool->SetShowMarkerNodes( false ); } } } } void QmitkSegmentationView::OnSelectionChanged(mitk::DataNode* node) { std::vector nodes; nodes.push_back( node ); this->OnSelectionChanged( nodes ); } void QmitkSegmentationView::OnSelectionChanged(std::vector nodes) { if (nodes.size() != 0) { std::string markerName = "Position"; unsigned int numberOfNodes = nodes.size(); std::string nodeName = nodes.at( 0 )->GetName(); if ( ( numberOfNodes == 1 ) && ( nodeName.find( markerName ) == 0) ) { this->OnContourMarkerSelected( nodes.at( 0 ) ); return; } } if (m_AutoSelectionEnabled && this->IsActivated()) { if (nodes.size() == 0 && m_Controls->patImageSelector->GetSelectedNode().IsNull()) { SetToolManagerSelection(NULL,NULL); } else if (nodes.size() == 1) { mitk::DataNode::Pointer selectedNode = nodes.at(0); if(selectedNode.IsNull()) { return; } mitk::Image::Pointer selectedImage = dynamic_cast(selectedNode->GetData()); if (selectedImage.IsNull()) { SetToolManagerSelection(NULL,NULL); return; } else { bool isASegmentation(false); selectedNode->GetBoolProperty("binary", isASegmentation); if (isASegmentation) { //If a segmentation is selected find a possible reference image: mitk::DataStorage::SetOfObjects::ConstPointer sources = this->GetDataStorage()->GetSources(selectedNode, m_IsNotABinaryImagePredicate); mitk::DataNode::Pointer refNode; if (sources->Size() != 0) { refNode = sources->ElementAt(0); refNode->SetVisibility(true); selectedNode->SetVisibility(true); SetToolManagerSelection(refNode,selectedNode); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } } else { mitk::DataStorage::SetOfObjects::ConstPointer possiblePatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possiblePatientImages->Begin(); it != possiblePatientImages->End(); it++) { refNode = it->Value(); if (this->CheckForSameGeometry(selectedNode, it->Value())) { refNode->SetVisibility(true); selectedNode->SetVisibility(true); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } this->SetToolManagerSelection(refNode, selectedNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are at the //same level in the datamanager int layer(10); refNode->GetIntProperty("layer", layer); layer++; selectedNode->SetProperty("layer", mitk::IntProperty::New(layer)); return; } } this->SetToolManagerSelection(NULL, selectedNode); } } else { if (mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0) != selectedNode) { SetToolManagerSelection(selectedNode, NULL); //May be a bug in the selection services. A node which is deselected will be passed as selected node to the OnSelectionChanged function if (!selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) selectedNode->SetVisibility(true); this->UpdateWarningLabel("The selected patient image does not\nmatchwith the selected segmentation!"); this->SetToolSelectionBoxesEnabled( false ); } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if ( m_Controls->lblSegmentationWarnings->isVisible()) // "RenderingManagerReinitialized()" caused a warning. we do not need to go any further return; RenderingManagerReinitialized(); } } void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode *node) { QmitkRenderWindow* selectedRenderWindow = 0; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } // make node visible if (selectedRenderWindow) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; { ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); context->ungetService(ppmRef); } selectedRenderWindow->GetRenderer()->GetDisplayGeometry()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnTabWidgetChanged(int id) { //always disable tools on tab changed mitk::ToolManagerProvider::GetInstance()->GetToolManager()->ActivateTool(-1); //2D Tab ID = 0 //3D Tab ID = 1 if (id == 0) { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); //Deactivate possible active tool //TODO Remove possible visible interpolations -> Maybe changes in SlicesInterpolator } else { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox2D->hide(); m_Controls->m_ManualToolSelectionBox3D->show(); //Deactivate possible active tool } } void QmitkSegmentationView::SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData) { // called as a result of new BlueBerry selections // tells the ToolManager for manual segmentation about new selections // updates GUI information about what the user should select mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); toolManager->SetReferenceData(const_cast(referenceData)); toolManager->SetWorkingData( const_cast(workingData)); // check original image m_Controls->btnNewSegmentation->setEnabled(referenceData != NULL); if (referenceData) { this->UpdateWarningLabel(""); disconnect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->patImageSelector->setCurrentIndex( m_Controls->patImageSelector->Find(referenceData) ); connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); } // check segmentation if (referenceData) { if (workingData) { this->FireNodeSelected(const_cast(workingData)); // if( m_Controls->widgetStack->currentIndex() == 0 ) // { disconnect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->segImageSelector->setCurrentIndex(m_Controls->segImageSelector->Find(workingData)); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged(const mitk::DataNode*)) ); // } } } } void QmitkSegmentationView::ForceDisplayPreferencesUponAllImages() { if (!m_Parent || !m_Parent->isVisible()) return; // check all images and segmentations in DataStorage: // (items in brackets are implicitly done by previous steps) // 1. // if a reference image is selected, // show the reference image // and hide all other images (orignal and segmentation), // (and hide all segmentations of the other original images) // and show all the reference's segmentations // if no reference image is selected, do do nothing // // 2. // if a segmentation is selected, // show it // (and hide all all its siblings (childs of the same parent, incl, NULL parent)) // if no segmentation is selected, do nothing if (!m_Controls) return; // might happen on initialization (preferences loaded) mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); mitk::DataNode::Pointer referenceData = toolManager->GetReferenceData(0); mitk::DataNode::Pointer workingData = toolManager->GetWorkingData(0); // 1. if (referenceData.IsNotNull()) { // iterate all images mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDefaultDataStorage()->GetSubset( m_IsABinaryImagePredicate ); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { mitk::DataNode* node = *iter; // apply display preferences ApplyDisplayOptions(node); // set visibility node->SetVisibility(node == referenceData); } } // 2. if (workingData.IsNotNull()) workingData->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (!node) return; bool isBinary(false); node->GetPropertyValue("binary", isBinary); if (isBinary) { node->SetProperty( "outline binary", mitk::BoolProperty::New( this->GetPreferences()->GetBool("draw outline", true)) ); node->SetProperty( "outline width", mitk::FloatProperty::New( 2.0 ) ); node->SetProperty( "opacity", mitk::FloatProperty::New( this->GetPreferences()->GetBool("draw outline", true) ? 1.0 : 0.3 ) ); node->SetProperty( "volumerendering", mitk::BoolProperty::New( this->GetPreferences()->GetBool("volume rendering", false) ) ); } } void QmitkSegmentationView::RenderingManagerReinitialized() { if ( ! m_MultiWidget ) { return; } /* * Here we check whether the geometry of the selected segmentation image if aligned with the worldgeometry * At the moment it is not supported to use a geometry different from the selected image for reslicing. * For further information see Bug 16063 */ mitk::DataNode* workingNode = m_Controls->segImageSelector->GetSelectedNode(); const mitk::BaseGeometry* worldGeo = m_MultiWidget->GetRenderWindow4()->GetSliceNavigationController()->GetCurrentGeometry3D(); if (workingNode && worldGeo) { const mitk::BaseGeometry* workingNodeGeo = workingNode->GetData()->GetGeometry(); const mitk::BaseGeometry* worldGeo = m_MultiWidget->GetRenderWindow4()->GetSliceNavigationController()->GetCurrentGeometry3D(); - if (mitk::Equal(workingNodeGeo->GetBoundingBox(), worldGeo->GetBoundingBox(), mitk::eps, true)) + if (mitk::Equal(*workingNodeGeo->GetBoundingBox(), *worldGeo->GetBoundingBox(), mitk::eps, true)) { this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), workingNode); this->SetToolSelectionBoxesEnabled(true); this->UpdateWarningLabel(""); } else { this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), NULL); this->SetToolSelectionBoxesEnabled(false); this->UpdateWarningLabel("Please perform a reinit on the segmentation image!"); } } } bool QmitkSegmentationView::CheckForSameGeometry(const mitk::DataNode *node1, const mitk::DataNode *node2) const { bool isSameGeometry(true); mitk::Image* image1 = dynamic_cast(node1->GetData()); mitk::Image* image2 = dynamic_cast(node2->GetData()); if (image1 && image2) { mitk::BaseGeometry* geo1 = image1->GetGeometry(); mitk::BaseGeometry* geo2 = image2->GetGeometry(); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetOrigin(), geo2->GetOrigin()); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(0), geo2->GetExtent(0)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(1), geo2->GetExtent(1)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(2), geo2->GetExtent(2)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetSpacing(), geo2->GetSpacing()); isSameGeometry = isSameGeometry && mitk::MatrixEqualElementWise(geo1->GetIndexToWorldTransform()->GetMatrix(), geo2->GetIndexToWorldTransform()->GetMatrix()); return isSameGeometry; } else { return false; } } void QmitkSegmentationView::UpdateWarningLabel(QString text) { if (text.size() == 0) m_Controls->lblSegmentationWarnings->hide(); else m_Controls->lblSegmentationWarnings->show(); m_Controls->lblSegmentationWarnings->setText(text); } void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { // setup the basic GUI of this view m_Parent = parent; m_Controls = new Ui::QmitkSegmentationControls; m_Controls->setupUi(parent); m_Controls->patImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->patImageSelector->SetPredicate(mitk::NodePredicateAnd::New(m_IsNotABinaryImagePredicate, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer()); this->UpdateWarningLabel("Please load an image"); if( m_Controls->patImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel("Select or create a new segmentation"); m_Controls->segImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->segImageSelector->SetPredicate(mitk::NodePredicateAnd::New(m_IsABinaryImagePredicate, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer()); if( m_Controls->segImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel(""); mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); assert ( toolManager ); toolManager->SetDataStorage( *(this->GetDefaultDataStorage()) ); toolManager->InitializeTools(); // all part of open source MITK m_Controls->m_ManualToolSelectionBox2D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox2D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer2D ); m_Controls->m_ManualToolSelectionBox2D->SetDisplayedToolGroups("Add Subtract Correction Paint Wipe 'Region Growing' Fill Erase 'Live Wire' '2D Fast Marching'"); m_Controls->m_ManualToolSelectionBox2D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox2D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); connect( m_Controls->m_ManualToolSelectionBox2D, SIGNAL(ToolSelected(int)), this, SLOT(OnManualTool2DSelected(int)) ); //setup 3D Tools m_Controls->m_ManualToolSelectionBox3D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox3D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer3D ); //specify tools to be added to 3D Tool area m_Controls->m_ManualToolSelectionBox3D->SetDisplayedToolGroups("Threshold 'UL Threshold' Otsu 'Fast Marching 3D' 'Region Growing 3D' Watershed Picking"); m_Controls->m_ManualToolSelectionBox3D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox3D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); toolManager->NewNodesGenerated += mitk::MessageDelegate( this, &QmitkSegmentationView::NewNodesGenerated ); // update the list of segmentations toolManager->NewNodeObjectsGenerated += mitk::MessageDelegate1( this, &QmitkSegmentationView::NewNodeObjectsGenerated ); // update the list of segmentations // create signal/slot connections connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->btnNewSegmentation, SIGNAL(clicked()), this, SLOT(CreateNewSegmentation()) ); // connect( m_Controls->CreateSegmentationFromSurface, SIGNAL(clicked()), this, SLOT(CreateSegmentationFromSurface()) ); // connect( m_Controls->widgetStack, SIGNAL(currentChanged(int)), this, SLOT(ToolboxStackPageChanged(int)) ); connect( m_Controls->tabWidgetSegmentationTools, SIGNAL(currentChanged(int)), this, SLOT(OnTabWidgetChanged(int))); // connect(m_Controls->MaskSurfaces, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), // this, SLOT( OnSurfaceSelectionChanged( ) ) ); connect(m_Controls->m_SlicesInterpolator, SIGNAL(SignalShowMarkerNodes(bool)), this, SLOT(OnShowMarkerNodes(bool))); // m_Controls->MaskSurfaces->SetDataStorage(this->GetDefaultDataStorage()); // m_Controls->MaskSurfaces->SetPredicate(mitk::NodePredicateDataType::New("Surface")); } void QmitkSegmentationView::OnManualTool2DSelected(int id) { if (id >= 0) { std::string text = "Active Tool: \""; mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); text += toolManager->GetToolById(id)->GetName(); text += "\""; mitk::StatusBar::GetInstance()->DisplayText(text.c_str()); us::ModuleResource resource = toolManager->GetToolById(id)->GetCursorIconResource(); this->SetMouseCursor(resource, 0, 0); } else { this->ResetMouseCursor(); mitk::StatusBar::GetInstance()->DisplayText(""); } } void QmitkSegmentationView::ResetMouseCursor() { if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); m_MouseCursorSet = false; } } void QmitkSegmentationView::SetMouseCursor( const us::ModuleResource& resource, int hotspotX, int hotspotY ) { if (!resource) return; // Remove previously set mouse cursor if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); } us::ModuleResourceStream cursor(resource, std::ios::binary); mitk::ApplicationCursor::GetInstance()->PushCursor( cursor, hotspotX, hotspotY ); m_MouseCursorSet = true; } void QmitkSegmentationView::SetToolSelectionBoxesEnabled(bool status) { if (status) { m_Controls->m_ManualToolSelectionBox2D->RecreateButtons(); m_Controls->m_ManualToolSelectionBox3D->RecreateButtons(); } m_Controls->m_ManualToolSelectionBox2D->setEnabled(status); m_Controls->m_ManualToolSelectionBox3D->setEnabled(status); m_Controls->m_SlicesInterpolator->setEnabled(status); } // ATTENTION some methods for handling the known list of (organ names, colors) are defined in QmitkSegmentationOrganNamesHandling.cpp diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp index d1609d5dd2..1f8fe85158 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp @@ -1,55 +1,71 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPluginActivator.h" #include "QmitkSegmentationView.h" #include "QmitkThresholdAction.h" #include "QmitkCreatePolygonModelAction.h" #include "QmitkAutocropAction.h" #include "QmitkSegmentationPreferencePage.h" #include "QmitkDeformableClippingPlaneView.h" #include "SegmentationUtilities/QmitkSegmentationUtilitiesView.h" using namespace mitk; -ctkPluginContext* PluginActivator::m_context = NULL; +ctkPluginContext* PluginActivator::m_context = nullptr; +PluginActivator* PluginActivator::m_Instance = nullptr; + +PluginActivator::PluginActivator() +{ + m_Instance = this; +} + +PluginActivator::~PluginActivator() +{ + m_Instance = nullptr; +} void PluginActivator::start(ctkPluginContext *context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkThresholdAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkCreatePolygonModelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDeformableClippingPlaneView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationUtilitiesView, context) this->m_context = context; } void PluginActivator::stop(ctkPluginContext *) { this->m_context = NULL; } +PluginActivator* PluginActivator::getDefault() +{ + return m_Instance; +} + ctkPluginContext*PluginActivator::getContext() { return m_context; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_segmentation, mitk::PluginActivator) #endif diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h index d546da48a7..a3b235119b 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h @@ -1,45 +1,51 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H // Parent classes -#include -#include +#include namespace mitk { - class PluginActivator : public QObject, public ctkPluginActivator + class PluginActivator : public berry::AbstractUICTKPlugin { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_segmentation") #endif Q_INTERFACES(ctkPluginActivator) public: + + PluginActivator(); + ~PluginActivator(); + void start(ctkPluginContext *context); void stop(ctkPluginContext *context); + static PluginActivator* getDefault(); + static ctkPluginContext* getContext(); private: static ctkPluginContext* m_context; + static PluginActivator* m_Instance; }; } #endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp index 7c8034c7d0..87ff8c3b35 100644 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp @@ -1,209 +1,209 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkSimulationPreferencePage.h" #include #include #include #include typedef sofa::helper::system::Plugin Plugin; typedef sofa::helper::system::PluginManager PluginManager; typedef sofa::helper::system::PluginManager::PluginIterator PluginIterator; typedef sofa::helper::system::PluginManager::PluginMap PluginMap; QmitkSimulationPreferencePage::QmitkSimulationPreferencePage() : m_Preferences(mitk::GetSimulationPreferences()), m_Control(NULL) { } QmitkSimulationPreferencePage::~QmitkSimulationPreferencePage() { } void QmitkSimulationPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_Controls.setupUi(m_Control); QStringList headerLabels; headerLabels << "Name" << "License" << "Version" << "Path"; m_Controls.pluginsTreeWidget->setHeaderLabels(headerLabels); connect(m_Controls.pluginsTreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(OnSelectedPluginChanged())); connect(m_Controls.addButton, SIGNAL(clicked()), this, SLOT(OnAddButtonClicked())); connect(m_Controls.removeButton, SIGNAL(clicked()), this, SLOT(OnRemoveButtonClicked())); this->Update(); } QWidget* QmitkSimulationPreferencePage::GetQtControl() const { return m_Control; } void QmitkSimulationPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkSimulationPreferencePage::OnAddButtonClicked() { QString filter = "SOFA Plugins "; #if defined(__APPLE__) filter += "(*.dylib*)"; #elif defined(WIN32) filter += "(*.dll)"; #else filter += "(*.so)"; #endif std::string path = QFileDialog::getOpenFileName(m_Control, "Add SOFA Plugin", "", filter).toStdString(); if (path.empty()) return; PluginManager &pluginManager = PluginManager::getInstance(); std::ostringstream errlog; if (pluginManager.loadPlugin(path, &errlog)) { if (!errlog.str().empty()) { QMessageBox* messageBox = new QMessageBox(m_Control); messageBox->setIcon(QMessageBox::Warning); messageBox->setStandardButtons(QMessageBox::Ok); messageBox->setText(errlog.str().c_str()); messageBox->setWindowTitle("Warning"); messageBox->show(); } Plugin& plugin = pluginManager.getPluginMap()[path]; plugin.initExternalModule(); QStringList pluginItem; pluginItem << plugin.getModuleName() << plugin.getModuleLicense() << plugin.getModuleVersion() << path.c_str(); m_Controls.pluginsTreeWidget->addTopLevelItem(new QTreeWidgetItem(pluginItem)); } else { QMessageBox* messageBox = new QMessageBox(m_Control); messageBox->setIcon(QMessageBox::Critical); messageBox->setStandardButtons(QMessageBox::Ok); messageBox->setText(errlog.str().c_str()); messageBox->setWindowTitle("Error"); messageBox->show(); } } void QmitkSimulationPreferencePage::OnSelectedPluginChanged() { QList selectedItems = m_Controls.pluginsTreeWidget->selectedItems(); m_Controls.componentsListWidget->clear(); if (!selectedItems.isEmpty()) { PluginMap& pluginMap = sofa::helper::system::PluginManager::getInstance().getPluginMap(); std::string path = selectedItems[0]->text(3).toStdString(); m_Controls.descriptionPlainTextEdit->setPlainText(pluginMap[path].getModuleDescription()); m_Controls.componentsListWidget->addItems(QString(pluginMap[path].getModuleComponentList()).split(' ', QString::SkipEmptyParts)); m_Controls.removeButton->setEnabled(true); } else { m_Controls.descriptionPlainTextEdit->clear(); m_Controls.removeButton->setEnabled(false); } } void QmitkSimulationPreferencePage::OnRemoveButtonClicked() { QList selectedItems = m_Controls.pluginsTreeWidget->selectedItems(); if (selectedItems.isEmpty()) return; std::string path = selectedItems[0]->text(3).toStdString(); PluginManager& pluginManager = PluginManager::getInstance(); std::ostringstream errlog; if (pluginManager.unloadPlugin(path, &errlog)) { delete selectedItems[0]; } else { QMessageBox* messageBox = new QMessageBox(m_Control); messageBox->setIcon(QMessageBox::Critical); messageBox->setStandardButtons(QMessageBox::Ok); messageBox->setText(errlog.str().c_str()); messageBox->setWindowTitle("Error"); messageBox->show(); } } void QmitkSimulationPreferencePage::PerformCancel() { } bool QmitkSimulationPreferencePage::PerformOk() { PluginManager& pluginManager = PluginManager::getInstance(); PluginMap& pluginMap = pluginManager.getPluginMap(); - std::string plugins; + QString plugins; for (PluginIterator it = pluginMap.begin(); it != pluginMap.end(); ++it) { - if (!plugins.empty()) + if (!plugins.isEmpty()) plugins += ";"; - plugins += it->first; + plugins += QString::fromStdString(it->first); } - m_Preferences->PutByteArray("plugins", plugins); + m_Preferences->Put("plugins", plugins); return true; } void QmitkSimulationPreferencePage::Update() { PluginManager& pluginManager = PluginManager::getInstance(); PluginMap& pluginMap = pluginManager.getPluginMap(); for (PluginIterator it = pluginMap.begin(); it != pluginMap.end(); ++it) { Plugin& plugin = it->second; QStringList pluginItem; pluginItem << plugin.getModuleName() << plugin.getModuleLicense() << plugin.getModuleVersion() << it->first.c_str(); m_Controls.pluginsTreeWidget->addTopLevelItem(new QTreeWidgetItem(pluginItem)); } } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp index 53f687e611..01088e2ff1 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp @@ -1,559 +1,558 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkStdMultiWidgetEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkStdMultiWidgetEditorPrivate { public: QmitkStdMultiWidgetEditorPrivate(); ~QmitkStdMultiWidgetEditorPrivate(); QmitkStdMultiWidget* m_StdMultiWidget; QmitkMouseModeSwitcher* m_MouseModeToolbar; /** * @brief Members for the MultiWidget decorations. */ - std::string m_WidgetBackgroundColor1[4]; - std::string m_WidgetBackgroundColor2[4]; - std::string m_WidgetDecorationColor[4]; - std::string m_WidgetAnnotation[4]; + QString m_WidgetBackgroundColor1[4]; + QString m_WidgetBackgroundColor2[4]; + QString m_WidgetDecorationColor[4]; + QString m_WidgetAnnotation[4]; bool m_MenuWidgetsEnabled; QScopedPointer m_PartListener; QHash m_RenderWindows; }; struct QmitkStdMultiWidgetPartListener : public berry::IPartListener { berryObjectMacro(QmitkStdMultiWidgetPartListener) QmitkStdMultiWidgetPartListener(QmitkStdMultiWidgetEditorPrivate* dd) : d(dd) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->AddPlanesToDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(true); } } } private: QmitkStdMultiWidgetEditorPrivate* const d; }; QmitkStdMultiWidgetEditorPrivate::QmitkStdMultiWidgetEditorPrivate() : m_StdMultiWidget(0), m_MouseModeToolbar(0) , m_MenuWidgetsEnabled(false) , m_PartListener(new QmitkStdMultiWidgetPartListener(this)) {} QmitkStdMultiWidgetEditorPrivate::~QmitkStdMultiWidgetEditorPrivate() { } const QString QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : d(new QmitkStdMultiWidgetEditorPrivate) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { this->GetSite()->GetPage()->RemovePartListener(d->m_PartListener.data()); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return d->m_StdMultiWidget; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetActiveQmitkRenderWindow() const { if (d->m_StdMultiWidget) return d->m_StdMultiWidget->GetRenderWindow1(); return 0; } QHash QmitkStdMultiWidgetEditor::GetQmitkRenderWindows() const { return d->m_RenderWindows; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetQmitkRenderWindow(const QString &id) const { if (d->m_RenderWindows.contains(id)) return d->m_RenderWindows[id]; return 0; } mitk::Point3D QmitkStdMultiWidgetEditor::GetSelectedPosition(const QString & /*id*/) const { return d->m_StdMultiWidget->GetCrossPosition(); } void QmitkStdMultiWidgetEditor::SetSelectedPosition(const mitk::Point3D &pos, const QString &/*id*/) { d->m_StdMultiWidget->MoveCrossToPosition(pos); } void QmitkStdMultiWidgetEditor::EnableDecorations(bool enable, const QStringList &decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_BORDER)) { enable ? d->m_StdMultiWidget->EnableColoredRectangles() : d->m_StdMultiWidget->DisableColoredRectangles(); } if (decorations.isEmpty() || decorations.contains(DECORATION_LOGO)) { enable ? d->m_StdMultiWidget->EnableDepartmentLogo() : d->m_StdMultiWidget->DisableDepartmentLogo(); } if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { d->m_StdMultiWidget->ActivateMenuWidget(enable); } if (decorations.isEmpty() || decorations.contains(DECORATION_BACKGROUND)) { enable ? d->m_StdMultiWidget->EnableGradientBackground() : d->m_StdMultiWidget->DisableGradientBackground(); } } bool QmitkStdMultiWidgetEditor::IsDecorationEnabled(const QString &decoration) const { if (decoration == DECORATION_BORDER) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_LOGO) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_MENU) { return d->m_StdMultiWidget->IsMenuWidgetEnabled(); } else if (decoration == DECORATION_BACKGROUND) { return d->m_StdMultiWidget->GetGradientBackgroundFlag(); } return false; } QStringList QmitkStdMultiWidgetEditor::GetDecorations() const { QStringList decorations; decorations << DECORATION_BORDER << DECORATION_LOGO << DECORATION_MENU << DECORATION_BACKGROUND; return decorations; } mitk::SlicesRotator* QmitkStdMultiWidgetEditor::GetSlicesRotator() const { return d->m_StdMultiWidget->GetSlicesRotator(); } mitk::SlicesSwiveller* QmitkStdMultiWidgetEditor::GetSlicesSwiveller() const { return d->m_StdMultiWidget->GetSlicesSwiveller(); } void QmitkStdMultiWidgetEditor::EnableSlicingPlanes(bool enable) { d->m_StdMultiWidget->SetWidgetPlanesVisibility(enable); } bool QmitkStdMultiWidgetEditor::IsSlicingPlanesEnabled() const { mitk::DataNode::Pointer node = this->d->m_StdMultiWidget->GetWidgetPlane1(); if (node.IsNotNull()) { bool visible = false; node->GetVisibility(visible, 0); return visible; } else { return false; } } void QmitkStdMultiWidgetEditor::EnableLinkedNavigation(bool enable) { enable ? d->m_StdMultiWidget->EnableNavigationControllerEventListening() : d->m_StdMultiWidget->DisableNavigationControllerEventListening(); } bool QmitkStdMultiWidgetEditor::IsLinkedNavigationEnabled() const { return d->m_StdMultiWidget->IsCrosshairNavigationEnabled(); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (d->m_StdMultiWidget == 0) { QHBoxLayout* layout = new QHBoxLayout(parent); layout->setContentsMargins(0,0,0,0); if (d->m_MouseModeToolbar == NULL) { d->m_MouseModeToolbar = new QmitkMouseModeSwitcher(parent); // delete by Qt via parent layout->addWidget(d->m_MouseModeToolbar); } berry::IPreferences::Pointer prefs = this->GetPreferences(); mitk::BaseRenderer::RenderingMode::Type renderingMode = static_cast(prefs->GetInt( "Rendering Mode" , 0 )); d->m_StdMultiWidget = new QmitkStdMultiWidget(parent,0,0,renderingMode); d->m_RenderWindows.insert("axial", d->m_StdMultiWidget->GetRenderWindow1()); d->m_RenderWindows.insert("sagittal", d->m_StdMultiWidget->GetRenderWindow2()); d->m_RenderWindows.insert("coronal", d->m_StdMultiWidget->GetRenderWindow3()); d->m_RenderWindows.insert("3d", d->m_StdMultiWidget->GetRenderWindow4()); d->m_MouseModeToolbar->setMouseModeSwitcher( d->m_StdMultiWidget->GetMouseModeSwitcher() ); connect( d->m_MouseModeToolbar, SIGNAL( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ), d->m_StdMultiWidget, SLOT( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ) ); layout->addWidget(d->m_StdMultiWidget); mitk::DataStorage::Pointer ds = this->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render d->m_StdMultiWidget->SetDataStorage(ds); // Initialize views as axial, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view d->m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider d->m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D d->m_StdMultiWidget->AddDisplayPlaneSubTree(); d->m_StdMultiWidget->EnableNavigationControllerEventListening(); // Store the initial visibility status of the menu widget. d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); this->GetSite()->GetPage()->AddPartListener(d->m_PartListener.data()); berry::IBerryPreferences* berryprefs = dynamic_cast(prefs.GetPointer()); InitializePreferences(berryprefs); this->OnPreferencesChanged(berryprefs); this->RequestUpdate(); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // Enable change of logo. If no DepartmentLogo was set explicitly, MBILogo is used. // Set new department logo by prefs->Set("DepartmentLogo", "PathToImage"); // If no logo was set for this plug-in specifically, walk the parent preference nodes // and lookup a logo value there. const berry::IPreferences* currentNode = prefs; while(currentNode) { bool logoFound = false; foreach (const QString& key, prefs->Keys()) { if( key == "DepartmentLogo") { QString departmentLogoLocation = prefs->Get("DepartmentLogo", ""); if (departmentLogoLocation.isEmpty()) { d->m_StdMultiWidget->DisableDepartmentLogo(); } else { // we need to disable the logo first, otherwise setting a new logo will have // no effect due to how mitkManufacturerLogo works... d->m_StdMultiWidget->DisableDepartmentLogo(); d->m_StdMultiWidget->SetDepartmentLogoPath(qPrintable(departmentLogoLocation)); d->m_StdMultiWidget->EnableDepartmentLogo(); } logoFound = true; break; } } if (logoFound) break; currentNode = currentNode->Parent().GetPointer(); } //Update internal members this->FillMembersWithCurrentDecorations(); this->GetPreferenceDecorations(prefs); //Now the members can be used to modify the stdmultiwidget mitk::Color upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[0]); mitk::Color lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[0]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 0); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[1]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[1]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 1); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[2]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[2]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 2); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[3]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[3]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 3); d->m_StdMultiWidget->EnableGradientBackground(); // preferences for renderWindows mitk::Color colorDecorationWidget1 = HexColorToMitkColor(d->m_WidgetDecorationColor[0]); mitk::Color colorDecorationWidget2 = HexColorToMitkColor(d->m_WidgetDecorationColor[1]); mitk::Color colorDecorationWidget3 = HexColorToMitkColor(d->m_WidgetDecorationColor[2]); mitk::Color colorDecorationWidget4 = HexColorToMitkColor(d->m_WidgetDecorationColor[3]); d->m_StdMultiWidget->SetDecorationColor(0, colorDecorationWidget1); d->m_StdMultiWidget->SetDecorationColor(1, colorDecorationWidget2); d->m_StdMultiWidget->SetDecorationColor(2, colorDecorationWidget3); d->m_StdMultiWidget->SetDecorationColor(3, colorDecorationWidget4); for(unsigned int i = 0; i < 4; ++i) { - d->m_StdMultiWidget->SetCornerAnnotation(d->m_WidgetAnnotation[i], + d->m_StdMultiWidget->SetCornerAnnotation(d->m_WidgetAnnotation[i].toStdString(), HexColorToMitkColor(d->m_WidgetDecorationColor[i]), i); } //The crosshair gap int crosshairgapsize = prefs->GetInt("crosshair gap size", 32); d->m_StdMultiWidget->GetWidgetPlane1()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); d->m_StdMultiWidget->GetWidgetPlane2()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); d->m_StdMultiWidget->GetWidgetPlane3()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); //refresh colors of rectangles d->m_StdMultiWidget->EnableColoredRectangles(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // level window setting bool showLevelWindowWidget = prefs->GetBool("Show level/window widget", true); if (showLevelWindowWidget) { d->m_StdMultiWidget->EnableStandardLevelWindow(); } else { d->m_StdMultiWidget->DisableStandardLevelWindow(); } // mouse modes toolbar bool newMode = prefs->GetBool("PACS like mouse interaction", false); d->m_MouseModeToolbar->setVisible( newMode ); d->m_StdMultiWidget->GetMouseModeSwitcher()->SetInteractionScheme( newMode ? mitk::MouseModeSwitcher::PACS : mitk::MouseModeSwitcher::MITK ); } -mitk::Color QmitkStdMultiWidgetEditor::HexColorToMitkColor(std::string widgetColorInHex) +mitk::Color QmitkStdMultiWidgetEditor::HexColorToMitkColor(const QString& widgetColorInHex) { - QString widgetColorQt = QString::fromStdString(widgetColorInHex); - QColor qColor(widgetColorQt); + QColor qColor(widgetColorInHex); mitk::Color returnColor; float colorMax = 255.0f; - if (widgetColorQt=="") // default value + if (widgetColorInHex.isEmpty()) // default value { returnColor[0] = 1.0; returnColor[1] = 1.0; returnColor[2] = 1.0; - MITK_ERROR << "Using default color for unknown widget " << widgetColorInHex; + MITK_ERROR << "Using default color for unknown widget " << qPrintable(widgetColorInHex); } else { returnColor[0] = qColor.red() / colorMax; returnColor[1] = qColor.green() / colorMax; returnColor[2] = qColor.blue() / colorMax; } return returnColor; } -std::string QmitkStdMultiWidgetEditor::MitkColorToHex(mitk::Color color) +QString QmitkStdMultiWidgetEditor::MitkColorToHex(const mitk::Color& color) { QColor returnColor; float colorMax = 255.0f; returnColor.setRed(static_cast(color[0]* colorMax + 0.5)); returnColor.setGreen(static_cast(color[1]* colorMax + 0.5)); returnColor.setBlue(static_cast(color[2]* colorMax + 0.5)); - return returnColor.name().toStdString(); + return returnColor.name(); } void QmitkStdMultiWidgetEditor::FillMembersWithCurrentDecorations() { //fill members with current values (or default values) from the std multi widget for(unsigned int i = 0; i < 4; ++i) { d->m_WidgetDecorationColor[i] = MitkColorToHex(d->m_StdMultiWidget->GetDecorationColor(i)); d->m_WidgetBackgroundColor1[i] = MitkColorToHex(d->m_StdMultiWidget->GetGradientColors(i).first); d->m_WidgetBackgroundColor2[i] = MitkColorToHex(d->m_StdMultiWidget->GetGradientColors(i).second); - d->m_WidgetAnnotation[i] = d->m_StdMultiWidget->GetCornerAnnotationText(i); + d->m_WidgetAnnotation[i] = QString::fromStdString(d->m_StdMultiWidget->GetCornerAnnotationText(i)); } } void QmitkStdMultiWidgetEditor::GetPreferenceDecorations(const berry::IBerryPreferences * preferences) { //overwrite members with values from the preferences, if they the prefrence is defined - d->m_WidgetBackgroundColor1[0] = preferences->GetByteArray("widget1 first background color", d->m_WidgetBackgroundColor1[0]); - d->m_WidgetBackgroundColor2[0] = preferences->GetByteArray("widget1 second background color", d->m_WidgetBackgroundColor2[0]); - d->m_WidgetBackgroundColor1[1] = preferences->GetByteArray("widget2 first background color", d->m_WidgetBackgroundColor1[1]); - d->m_WidgetBackgroundColor2[1] = preferences->GetByteArray("widget2 second background color", d->m_WidgetBackgroundColor2[1]); - d->m_WidgetBackgroundColor1[2] = preferences->GetByteArray("widget3 first background color", d->m_WidgetBackgroundColor1[2]); - d->m_WidgetBackgroundColor2[2] = preferences->GetByteArray("widget3 second background color", d->m_WidgetBackgroundColor2[2]); - d->m_WidgetBackgroundColor1[3] = preferences->GetByteArray("widget4 first background color", d->m_WidgetBackgroundColor1[3]); - d->m_WidgetBackgroundColor2[3] = preferences->GetByteArray("widget4 second background color", d->m_WidgetBackgroundColor2[3]); - - d->m_WidgetDecorationColor[0] = preferences->GetByteArray("widget1 decoration color", d->m_WidgetDecorationColor[0]); - d->m_WidgetDecorationColor[1] = preferences->GetByteArray("widget2 decoration color", d->m_WidgetDecorationColor[1]); - d->m_WidgetDecorationColor[2] = preferences->GetByteArray("widget3 decoration color", d->m_WidgetDecorationColor[2]); - d->m_WidgetDecorationColor[3] = preferences->GetByteArray("widget4 decoration color", d->m_WidgetDecorationColor[3]); - - d->m_WidgetAnnotation[0] = preferences->GetByteArray("widget1 corner annotation", d->m_WidgetAnnotation[0]); - d->m_WidgetAnnotation[1] = preferences->GetByteArray("widget2 corner annotation", d->m_WidgetAnnotation[1]); - d->m_WidgetAnnotation[2] = preferences->GetByteArray("widget3 corner annotation", d->m_WidgetAnnotation[2]); - d->m_WidgetAnnotation[3] = preferences->GetByteArray("widget4 corner annotation", d->m_WidgetAnnotation[3]); + d->m_WidgetBackgroundColor1[0] = preferences->Get("widget1 first background color", d->m_WidgetBackgroundColor1[0]); + d->m_WidgetBackgroundColor2[0] = preferences->Get("widget1 second background color", d->m_WidgetBackgroundColor2[0]); + d->m_WidgetBackgroundColor1[1] = preferences->Get("widget2 first background color", d->m_WidgetBackgroundColor1[1]); + d->m_WidgetBackgroundColor2[1] = preferences->Get("widget2 second background color", d->m_WidgetBackgroundColor2[1]); + d->m_WidgetBackgroundColor1[2] = preferences->Get("widget3 first background color", d->m_WidgetBackgroundColor1[2]); + d->m_WidgetBackgroundColor2[2] = preferences->Get("widget3 second background color", d->m_WidgetBackgroundColor2[2]); + d->m_WidgetBackgroundColor1[3] = preferences->Get("widget4 first background color", d->m_WidgetBackgroundColor1[3]); + d->m_WidgetBackgroundColor2[3] = preferences->Get("widget4 second background color", d->m_WidgetBackgroundColor2[3]); + + d->m_WidgetDecorationColor[0] = preferences->Get("widget1 decoration color", d->m_WidgetDecorationColor[0]); + d->m_WidgetDecorationColor[1] = preferences->Get("widget2 decoration color", d->m_WidgetDecorationColor[1]); + d->m_WidgetDecorationColor[2] = preferences->Get("widget3 decoration color", d->m_WidgetDecorationColor[2]); + d->m_WidgetDecorationColor[3] = preferences->Get("widget4 decoration color", d->m_WidgetDecorationColor[3]); + + d->m_WidgetAnnotation[0] = preferences->Get("widget1 corner annotation", d->m_WidgetAnnotation[0]); + d->m_WidgetAnnotation[1] = preferences->Get("widget2 corner annotation", d->m_WidgetAnnotation[1]); + d->m_WidgetAnnotation[2] = preferences->Get("widget3 corner annotation", d->m_WidgetAnnotation[2]); + d->m_WidgetAnnotation[3] = preferences->Get("widget4 corner annotation", d->m_WidgetAnnotation[3]); } void QmitkStdMultiWidgetEditor::InitializePreferences(berry::IBerryPreferences * preferences) { this->FillMembersWithCurrentDecorations(); //fill members this->GetPreferenceDecorations(preferences); //overwrite if preferences are defined //create new preferences - preferences->PutByteArray("widget1 corner annotation", d->m_WidgetAnnotation[0]); - preferences->PutByteArray("widget2 corner annotation", d->m_WidgetAnnotation[1]); - preferences->PutByteArray("widget3 corner annotation", d->m_WidgetAnnotation[2]); - preferences->PutByteArray("widget4 corner annotation", d->m_WidgetAnnotation[3]); - - preferences->PutByteArray("widget1 decoration color", d->m_WidgetDecorationColor[0]); - preferences->PutByteArray("widget2 decoration color", d->m_WidgetDecorationColor[1]); - preferences->PutByteArray("widget3 decoration color", d->m_WidgetDecorationColor[2]); - preferences->PutByteArray("widget4 decoration color", d->m_WidgetDecorationColor[3]); - - preferences->PutByteArray("widget1 first background color", d->m_WidgetBackgroundColor1[0]); - preferences->PutByteArray("widget2 first background color", d->m_WidgetBackgroundColor1[1]); - preferences->PutByteArray("widget3 first background color", d->m_WidgetBackgroundColor1[2]); - preferences->PutByteArray("widget4 first background color", d->m_WidgetBackgroundColor1[3]); - preferences->PutByteArray("widget1 second background color", d->m_WidgetBackgroundColor2[0]); - preferences->PutByteArray("widget2 second background color", d->m_WidgetBackgroundColor2[1]); - preferences->PutByteArray("widget3 second background color", d->m_WidgetBackgroundColor2[2]); - preferences->PutByteArray("widget4 second background color", d->m_WidgetBackgroundColor2[3]); + preferences->Put("widget1 corner annotation", d->m_WidgetAnnotation[0]); + preferences->Put("widget2 corner annotation", d->m_WidgetAnnotation[1]); + preferences->Put("widget3 corner annotation", d->m_WidgetAnnotation[2]); + preferences->Put("widget4 corner annotation", d->m_WidgetAnnotation[3]); + + preferences->Put("widget1 decoration color", d->m_WidgetDecorationColor[0]); + preferences->Put("widget2 decoration color", d->m_WidgetDecorationColor[1]); + preferences->Put("widget3 decoration color", d->m_WidgetDecorationColor[2]); + preferences->Put("widget4 decoration color", d->m_WidgetDecorationColor[3]); + + preferences->Put("widget1 first background color", d->m_WidgetBackgroundColor1[0]); + preferences->Put("widget2 first background color", d->m_WidgetBackgroundColor1[1]); + preferences->Put("widget3 first background color", d->m_WidgetBackgroundColor1[2]); + preferences->Put("widget4 first background color", d->m_WidgetBackgroundColor1[3]); + preferences->Put("widget1 second background color", d->m_WidgetBackgroundColor2[0]); + preferences->Put("widget2 second background color", d->m_WidgetBackgroundColor2[1]); + preferences->Put("widget3 second background color", d->m_WidgetBackgroundColor2[2]); + preferences->Put("widget4 second background color", d->m_WidgetBackgroundColor2[3]); } void QmitkStdMultiWidgetEditor::SetFocus() { if (d->m_StdMultiWidget != 0) d->m_StdMultiWidget->setFocus(); } void QmitkStdMultiWidgetEditor::RequestActivateMenuWidget(bool on) { if (d->m_StdMultiWidget) { if (on) { d->m_StdMultiWidget->ActivateMenuWidget(d->m_MenuWidgetsEnabled); } else { d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); d->m_StdMultiWidget->ActivateMenuWidget(false); } } } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index c7d8784569..7045b9fb0b 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,154 +1,154 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkStdMultiWidgetEditor_h #define QmitkStdMultiWidgetEditor_h #include #include #include class QmitkStdMultiWidget; class QmitkMouseModeSwitcher; class QmitkStdMultiWidgetEditorPrivate; /** * \ingroup org_mitk_gui_qt_stdmultiwidgeteditor */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor : public QmitkAbstractRenderEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: berryObjectMacro(QmitkStdMultiWidgetEditor); static const QString EDITOR_ID; QmitkStdMultiWidgetEditor(); ~QmitkStdMultiWidgetEditor(); QmitkStdMultiWidget* GetStdMultiWidget(); /// \brief If on=true will request the QmitkStdMultiWidget set the Menu widget to /// whatever was the last known enabled state, and if on=false will turn the Menu widget off. void RequestActivateMenuWidget(bool on); // ------------------- mitk::IRenderWindowPart ---------------------- /** * \see mitk::IRenderWindowPart::GetActiveQmitkRenderWindow() */ QmitkRenderWindow* GetActiveQmitkRenderWindow() const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindows() */ QHash GetQmitkRenderWindows() const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindow(QString) */ QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const; /** * \see mitk::IRenderWindowPart::GetSelectionPosition() */ mitk::Point3D GetSelectedPosition(const QString& id = QString()) const; /** * \see mitk::IRenderWindowPart::SetSelectedPosition() */ void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()); /** * \see mitk::IRenderWindowPart::EnableDecorations() */ void EnableDecorations(bool enable, const QStringList& decorations = QStringList()); /** * \see mitk::IRenderWindowPart::IsDecorationEnabled() */ bool IsDecorationEnabled(const QString& decoration) const; /** * \see mitk::IRenderWindowPart::GetDecorations() */ QStringList GetDecorations() const; // ------------------- mitk::ILinkedRenderWindowPart ---------------------- mitk::SlicesRotator* GetSlicesRotator() const; mitk::SlicesSwiveller* GetSlicesSwiveller() const; void EnableSlicingPlanes(bool enable); bool IsSlicingPlanesEnabled() const; void EnableLinkedNavigation(bool enable); bool IsLinkedNavigationEnabled() const; protected: /** * @brief FillMembersWithCurrentDecorations Helper method to fill internal members with * current values of the std multi widget. */ void FillMembersWithCurrentDecorations(); /** * @brief GetPreferenceDecorations Getter to fill internal members with values of preferences. * @param preferences The berry preferences. * * If a preference is set, the value will overwrite the current value. If it does not exist, * the value will not change. */ void GetPreferenceDecorations(const berry::IBerryPreferences *preferences); void SetFocus(); void OnPreferencesChanged(const berry::IBerryPreferences*); void CreateQtPartControl(QWidget* parent); /** * @brief GetColorForWidget helper method to convert a saved color string to mitk::Color. * @param widgetColorInHex color in hex format (#12356) where each diget is in the form (0-F). * @return the color in mitk format. */ - mitk::Color HexColorToMitkColor(std::string widgetColorInHex); + mitk::Color HexColorToMitkColor(const QString& widgetColorInHex); /** * @brief MitkColorToHex Convert an mitk::Color to hex string. * @param color mitk format. * @return String in hex (#RRGGBB). */ - std::string MitkColorToHex(mitk::Color color); + QString MitkColorToHex(const mitk::Color& color); /** * @brief InitializePreferences Internal helper method to set default preferences. * This method is used to show the current preferences in the first call of * the preference page (the GUI). * * @param preferences berry preferences. */ void InitializePreferences(berry::IBerryPreferences *preferences); private: const QScopedPointer d; }; #endif /*QmitkStdMultiWidgetEditor_h*/ diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp index 676b86ec54..ec9286ef1f 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.cpp @@ -1,277 +1,271 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "QmitkStdMultiWidgetEditorPreferencePage.h" #include #include #include #include QmitkStdMultiWidgetEditorPreferencePage::QmitkStdMultiWidgetEditorPreferencePage() : m_Preferences(NULL), m_Ui(new Ui::QmitkStdMultiWidgetEditorPreferencePage), m_Control(NULL) { } QmitkStdMultiWidgetEditorPreferencePage::~QmitkStdMultiWidgetEditorPreferencePage() { } void QmitkStdMultiWidgetEditorPreferencePage::CreateQtControl(QWidget* parent) { m_Control = new QWidget(parent); m_Ui->setupUi(m_Control); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); Q_ASSERT(prefService); m_Preferences = prefService->GetSystemPreferences()->Node(QmitkStdMultiWidgetEditor::EDITOR_ID); QObject::connect( m_Ui->m_ColorButton1, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ColorButton2, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_ResetButton, SIGNAL( clicked() ) , this, SLOT( ResetPreferencesAndGUI() ) ); QObject::connect( m_Ui->m_RenderingMode, SIGNAL(activated(int) ) , this, SLOT( ChangeRenderingMode(int) ) ); QObject::connect( m_Ui->m_RenderWindowDecorationColor, SIGNAL( clicked() ) , this, SLOT( ColorChooserButtonClicked() ) ); QObject::connect( m_Ui->m_RenderWindowChooser, SIGNAL(activated(int) ) , this, SLOT( OnWidgetComboBoxChanged(int) ) ); QObject::connect( m_Ui->m_RenderWindowDecorationText, SIGNAL(textChanged(QString) ) , this, SLOT( AnnotationTextChanged(QString) ) ); this->Update(); } QWidget* QmitkStdMultiWidgetEditorPreferencePage::GetQtControl() const { return m_Control; } void QmitkStdMultiWidgetEditorPreferencePage::Init(berry::IWorkbench::Pointer) { } void QmitkStdMultiWidgetEditorPreferencePage::PerformCancel() { } bool QmitkStdMultiWidgetEditorPreferencePage::PerformOk() { - m_Preferences->PutByteArray("widget1 corner annotation", m_WidgetAnnotation[0]); - m_Preferences->PutByteArray("widget2 corner annotation", m_WidgetAnnotation[1]); - m_Preferences->PutByteArray("widget3 corner annotation", m_WidgetAnnotation[2]); - m_Preferences->PutByteArray("widget4 corner annotation", m_WidgetAnnotation[3]); - - m_Preferences->PutByteArray("widget1 decoration color", m_WidgetDecorationColor[0]); - m_Preferences->PutByteArray("widget2 decoration color", m_WidgetDecorationColor[1]); - m_Preferences->PutByteArray("widget3 decoration color", m_WidgetDecorationColor[2]); - m_Preferences->PutByteArray("widget4 decoration color", m_WidgetDecorationColor[3]); - - m_Preferences->PutByteArray("widget1 first background color", m_WidgetBackgroundColor1[0]); - m_Preferences->PutByteArray("widget2 first background color", m_WidgetBackgroundColor1[1]); - m_Preferences->PutByteArray("widget3 first background color", m_WidgetBackgroundColor1[2]); - m_Preferences->PutByteArray("widget4 first background color", m_WidgetBackgroundColor1[3]); - m_Preferences->PutByteArray("widget1 second background color", m_WidgetBackgroundColor2[0]); - m_Preferences->PutByteArray("widget2 second background color", m_WidgetBackgroundColor2[1]); - m_Preferences->PutByteArray("widget3 second background color", m_WidgetBackgroundColor2[2]); - m_Preferences->PutByteArray("widget4 second background color", m_WidgetBackgroundColor2[3]); + m_Preferences->Put("widget1 corner annotation", m_WidgetAnnotation[0]); + m_Preferences->Put("widget2 corner annotation", m_WidgetAnnotation[1]); + m_Preferences->Put("widget3 corner annotation", m_WidgetAnnotation[2]); + m_Preferences->Put("widget4 corner annotation", m_WidgetAnnotation[3]); + + m_Preferences->Put("widget1 decoration color", m_WidgetDecorationColor[0]); + m_Preferences->Put("widget2 decoration color", m_WidgetDecorationColor[1]); + m_Preferences->Put("widget3 decoration color", m_WidgetDecorationColor[2]); + m_Preferences->Put("widget4 decoration color", m_WidgetDecorationColor[3]); + + m_Preferences->Put("widget1 first background color", m_WidgetBackgroundColor1[0]); + m_Preferences->Put("widget2 first background color", m_WidgetBackgroundColor1[1]); + m_Preferences->Put("widget3 first background color", m_WidgetBackgroundColor1[2]); + m_Preferences->Put("widget4 first background color", m_WidgetBackgroundColor1[3]); + m_Preferences->Put("widget1 second background color", m_WidgetBackgroundColor2[0]); + m_Preferences->Put("widget2 second background color", m_WidgetBackgroundColor2[1]); + m_Preferences->Put("widget3 second background color", m_WidgetBackgroundColor2[2]); + m_Preferences->Put("widget4 second background color", m_WidgetBackgroundColor2[3]); m_Preferences->PutInt("crosshair gap size", m_Ui->m_CrosshairGapSize->value()); m_Preferences->PutBool("Use constrained zooming and padding" , m_Ui->m_EnableFlexibleZooming->isChecked()); m_Preferences->PutBool("Show level/window widget", m_Ui->m_ShowLevelWindowWidget->isChecked()); m_Preferences->PutBool("PACS like mouse interaction", m_Ui->m_PACSLikeMouseMode->isChecked()); m_Preferences->PutInt("Rendering Mode", m_Ui->m_RenderingMode->currentIndex()); return true; } void QmitkStdMultiWidgetEditorPreferencePage::Update() { //Note: there should be default preferences already defined in the //QmitkStdMultiWidgetEditor::InitializePreferences(). Therefore, //all default values here are not relevant. //gradient background colors - m_WidgetBackgroundColor1[0] = m_Preferences->GetByteArray("widget1 first background color", "#000000"); - m_WidgetBackgroundColor2[0] = m_Preferences->GetByteArray("widget1 second background color", "#000000"); - m_WidgetBackgroundColor1[1] = m_Preferences->GetByteArray("widget2 first background color", "#000000"); - m_WidgetBackgroundColor2[1] = m_Preferences->GetByteArray("widget2 second background color", "#000000"); - m_WidgetBackgroundColor1[2] = m_Preferences->GetByteArray("widget3 first background color", "#000000"); - m_WidgetBackgroundColor2[2] = m_Preferences->GetByteArray("widget3 second background color", "#000000"); - m_WidgetBackgroundColor1[3] = m_Preferences->GetByteArray("widget4 first background color", "#191919"); - m_WidgetBackgroundColor2[3] = m_Preferences->GetByteArray("widget4 second background color", "#7F7F7F"); + m_WidgetBackgroundColor1[0] = m_Preferences->Get("widget1 first background color", "#000000"); + m_WidgetBackgroundColor2[0] = m_Preferences->Get("widget1 second background color", "#000000"); + m_WidgetBackgroundColor1[1] = m_Preferences->Get("widget2 first background color", "#000000"); + m_WidgetBackgroundColor2[1] = m_Preferences->Get("widget2 second background color", "#000000"); + m_WidgetBackgroundColor1[2] = m_Preferences->Get("widget3 first background color", "#000000"); + m_WidgetBackgroundColor2[2] = m_Preferences->Get("widget3 second background color", "#000000"); + m_WidgetBackgroundColor1[3] = m_Preferences->Get("widget4 first background color", "#191919"); + m_WidgetBackgroundColor2[3] = m_Preferences->Get("widget4 second background color", "#7F7F7F"); //decoration colors - m_WidgetDecorationColor[0] = m_Preferences->GetByteArray("widget1 decoration color", "#FF0000"); - m_WidgetDecorationColor[1] = m_Preferences->GetByteArray("widget2 decoration color", "#00FF00"); - m_WidgetDecorationColor[2] = m_Preferences->GetByteArray("widget3 decoration color", "#0000FF"); - m_WidgetDecorationColor[3] = m_Preferences->GetByteArray("widget4 decoration color", "#FFFF00"); + m_WidgetDecorationColor[0] = m_Preferences->Get("widget1 decoration color", "#FF0000"); + m_WidgetDecorationColor[1] = m_Preferences->Get("widget2 decoration color", "#00FF00"); + m_WidgetDecorationColor[2] = m_Preferences->Get("widget3 decoration color", "#0000FF"); + m_WidgetDecorationColor[3] = m_Preferences->Get("widget4 decoration color", "#FFFF00"); //annotation text - m_WidgetAnnotation[0] = m_Preferences->GetByteArray("widget1 corner annotation", "Axial"); - m_WidgetAnnotation[1] = m_Preferences->GetByteArray("widget2 corner annotation", "Sagittal"); - m_WidgetAnnotation[2] = m_Preferences->GetByteArray("widget3 corner annotation", "Coronal"); - m_WidgetAnnotation[3] = m_Preferences->GetByteArray("widget4 corner annotation", "3D"); + m_WidgetAnnotation[0] = m_Preferences->Get("widget1 corner annotation", "Axial"); + m_WidgetAnnotation[1] = m_Preferences->Get("widget2 corner annotation", "Sagittal"); + m_WidgetAnnotation[2] = m_Preferences->Get("widget3 corner annotation", "Coronal"); + m_WidgetAnnotation[3] = m_Preferences->Get("widget4 corner annotation", "3D"); //Ui stuff int index = m_Ui->m_RenderWindowChooser->currentIndex(); - QColor firstBackgroundColor = this->HexStringToQtColor(m_WidgetBackgroundColor1[index]); - QColor secondBackgroundColor = this->HexStringToQtColor(m_WidgetBackgroundColor2[index]); - QColor widgetColor = this->HexStringToQtColor(m_WidgetDecorationColor[index]); + QColor firstBackgroundColor(m_WidgetBackgroundColor1[index]); + QColor secondBackgroundColor(m_WidgetBackgroundColor2[index]); + QColor widgetColor(m_WidgetDecorationColor[index]); this->SetStyleSheetToColorChooserButton(firstBackgroundColor, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(secondBackgroundColor, m_Ui->m_ColorButton2); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); - m_Ui->m_RenderWindowDecorationText->setText(QString::fromStdString(m_WidgetAnnotation[index])); + m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[index]); m_Ui->m_EnableFlexibleZooming->setChecked(m_Preferences->GetBool("Use constrained zooming and padding", true)); m_Ui->m_ShowLevelWindowWidget->setChecked(m_Preferences->GetBool("Show level/window widget", true)); m_Ui->m_PACSLikeMouseMode->setChecked(m_Preferences->GetBool("PACS like mouse interaction", false)); int mode= m_Preferences->GetInt("Rendering Mode",0); m_Ui->m_RenderingMode->setCurrentIndex(mode); m_Ui->m_CrosshairGapSize->setValue(m_Preferences->GetInt("crosshair gap size", 32)); } -QColor QmitkStdMultiWidgetEditorPreferencePage::HexStringToQtColor(std::string colorInHex) -{ - QColor returncol; - returncol.setNamedColor(QString::fromStdString(colorInHex)); - return returncol; -} - void QmitkStdMultiWidgetEditorPreferencePage::ColorChooserButtonClicked() { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if(widgetIndex > 3) { MITK_ERROR << "Selected index for unknown."; return; } QObject *senderObj = sender(); // This will give Sender button //find out last used color and set it QColor initialColor; if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { - initialColor = HexStringToQtColor(m_WidgetBackgroundColor1[widgetIndex]); + initialColor = QColor(m_WidgetBackgroundColor1[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { - initialColor = HexStringToQtColor(m_WidgetBackgroundColor2[widgetIndex]); + initialColor = QColor(m_WidgetBackgroundColor2[widgetIndex]); }else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { - initialColor = HexStringToQtColor(m_WidgetDecorationColor[widgetIndex]); + initialColor = QColor(m_WidgetDecorationColor[widgetIndex]); } //get the new color QColor newcolor = QColorDialog::getColor(initialColor); if(!newcolor.isValid()) { newcolor = initialColor; } this->SetStyleSheetToColorChooserButton(newcolor, static_cast(senderObj)); //convert it to std string and apply it if( senderObj->objectName() == m_Ui->m_ColorButton1->objectName()) { - m_WidgetBackgroundColor1[widgetIndex] = newcolor.name().toStdString(); - }else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) + m_WidgetBackgroundColor1[widgetIndex] = newcolor.name(); + } + else if( senderObj->objectName() == m_Ui->m_ColorButton2->objectName()) { - m_WidgetBackgroundColor2[widgetIndex] = newcolor.name().toStdString(); - }else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) + m_WidgetBackgroundColor2[widgetIndex] = newcolor.name(); + } + else if( senderObj->objectName() == m_Ui->m_RenderWindowDecorationColor->objectName()) { - m_WidgetDecorationColor[widgetIndex] = newcolor.name().toStdString(); + m_WidgetDecorationColor[widgetIndex] = newcolor.name(); } } void QmitkStdMultiWidgetEditorPreferencePage::SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button) { button->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(backgroundcolor.red())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.green())); styleSheet.append(","); styleSheet.append(QString::number(backgroundcolor.blue())); styleSheet.append(")"); button->setStyleSheet(styleSheet); } void QmitkStdMultiWidgetEditorPreferencePage::AnnotationTextChanged(QString text) { unsigned int widgetIndex = m_Ui->m_RenderWindowChooser->currentIndex(); if( widgetIndex > 3) { MITK_INFO << "Selected index for unknown widget."; return; } - m_WidgetAnnotation[widgetIndex] = text.toStdString(); + m_WidgetAnnotation[widgetIndex] = text; } void QmitkStdMultiWidgetEditorPreferencePage::ResetPreferencesAndGUI() { m_Preferences->Clear(); this->Update(); } void QmitkStdMultiWidgetEditorPreferencePage::OnWidgetComboBoxChanged(int i) { if( i > 3) { MITK_ERROR << "Selected unknown widget."; return; } - QColor widgetColor, gradientBackground1, gradientBackground2; - widgetColor = HexStringToQtColor(m_WidgetDecorationColor[i]); - gradientBackground1 = HexStringToQtColor(m_WidgetBackgroundColor1[i]); - gradientBackground2 = HexStringToQtColor(m_WidgetBackgroundColor2[i]); + QColor widgetColor(m_WidgetDecorationColor[i]); + QColor gradientBackground1(m_WidgetBackgroundColor1[i]); + QColor gradientBackground2(m_WidgetBackgroundColor2[i]); this->SetStyleSheetToColorChooserButton(widgetColor, m_Ui->m_RenderWindowDecorationColor); this->SetStyleSheetToColorChooserButton(gradientBackground1, m_Ui->m_ColorButton1); this->SetStyleSheetToColorChooserButton(gradientBackground2, m_Ui->m_ColorButton2); - m_Ui->m_RenderWindowDecorationText->setText(QString::fromStdString(m_WidgetAnnotation[i])); + m_Ui->m_RenderWindowDecorationText->setText(m_WidgetAnnotation[i]); } void QmitkStdMultiWidgetEditorPreferencePage::ChangeRenderingMode(int i) { if( i == 0 ) { m_CurrentRenderingMode = "Standard"; } else if( i == 1 ) { m_CurrentRenderingMode = "Multisampling"; } else if( i == 2 ) { m_CurrentRenderingMode = "DepthPeeling"; } } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h index c9185d0a8d..d6a21ca140 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/internal/QmitkStdMultiWidgetEditorPreferencePage.h @@ -1,127 +1,120 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkStdMultiWidgetEditorPreferencePage_h #define QmitkStdMultiWidgetEditorPreferencePage_h #include #include #include #include #include namespace Ui { class QmitkStdMultiWidgetEditorPreferencePage; } class QmitkStdMultiWidgetEditorPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkStdMultiWidgetEditorPreferencePage(); ~QmitkStdMultiWidgetEditorPreferencePage(); void CreateQtControl(QWidget* parent); QWidget* GetQtControl() const; void Init(berry::IWorkbench::Pointer); void PerformCancel(); bool PerformOk(); void Update(); public slots: /** * @brief ResetColors set default colors and refresh the GUI. */ void ResetPreferencesAndGUI(); /** * @brief ChangeRenderingMode slot to chose the rendering mode via QComboBox. * @param i index of the box. */ void ChangeRenderingMode(int i); /** * @brief OnWidgetComboBoxChanged slot called when the QComboBox to chose the widget was modified. * @param i index of the combobox to select the widget (1-4). */ void OnWidgetComboBoxChanged(int i); /** * @brief AnnotationTextChanged called when QLineEdit for the annotation was changed. * @param text The new text. */ void AnnotationTextChanged(QString text); protected: /** * @brief m_CurrentRenderingMode String for the rendering mode. */ std::string m_CurrentRenderingMode; /** * @brief m_WidgetBackgroundColor1 the background colors. * * If two different colors are chosen, a gradient background appears. */ - std::string m_WidgetBackgroundColor1[4]; - std::string m_WidgetBackgroundColor2[4]; + QString m_WidgetBackgroundColor1[4]; + QString m_WidgetBackgroundColor2[4]; /** * @brief m_WidgetDecorationColor the decoration color. * * The rectangle prop, the crosshair, the 3D planes and the corner annotation use this. */ - std::string m_WidgetDecorationColor[4]; + QString m_WidgetDecorationColor[4]; /** * @brief m_Widget1Annotation the text of the corner annotation. */ - std::string m_WidgetAnnotation[4]; + QString m_WidgetAnnotation[4]; /** * @brief m_Preferences the berry preferences. */ berry::IPreferences::Pointer m_Preferences; /** * @brief SetStyleSheetToColorChooserButton colorize a button. * @param backgroundcolor color for the button. * @param button the button. */ void SetStyleSheetToColorChooserButton(QColor backgroundcolor, QPushButton* button); - /** - * @brief StringToColor convert a hexadecimal std::string to QColor. - * @param colorInHex string in the form of "#123456" where each digit is a hex value (0-F). - * @return color in Qt format. - */ - QColor HexStringToQtColor(std::string colorInHex); - protected slots: /** * @brief ColorChooserButtonClicked slot called when a button to choose color was clicked. */ void ColorChooserButtonClicked(); private: QScopedPointer m_Ui; QWidget* m_Control; }; #endif //QmitkStdMultiWidgetEditorPreferencePage_h diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp index ed52aebfde..76f1eaedb1 100644 --- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp +++ b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp @@ -1,301 +1,295 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkUGVisualizationView.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include class UGVisVolumeObserver : public mitk::PropertyView { public: UGVisVolumeObserver(mitk::BoolProperty* property, QmitkUGVisualizationView* view) : PropertyView(property), m_View(view), m_BoolProperty(property) { } protected: virtual void PropertyChanged() { m_View->m_VolumeMode = m_BoolProperty->GetValue(); m_View->UpdateEnablement(); } virtual void PropertyRemoved() { m_View->m_VolumeMode = false; m_Property = 0; m_BoolProperty = 0; } QmitkUGVisualizationView* m_View; mitk::BoolProperty* m_BoolProperty; }; const std::string QmitkUGVisualizationView::VIEW_ID = "org.mitk.views.ugvisualization"; QmitkUGVisualizationView::QmitkUGVisualizationView() : QmitkFunctionality(), m_MultiWidget(0), m_Outline2DAction(0), m_Outline2DWidget(0), m_LODAction(0), m_ScalarVisibilityAction(0), m_ScalarVisibilityWidget(0), m_FirstVolumeRepId(-1), m_ShowTFGeneratorWidget(true), m_ShowScalarOpacityWidget(false), m_ShowColorWidget(true), m_ShowGradientOpacityWidget(false), m_ShowTFGeneratorAction(0), m_ShowScalarOpacityAction(0), m_ShowColorAction(0), m_ShowGradientOpacityAction(0), m_VolumeModeObserver(0) { } -QmitkUGVisualizationView::QmitkUGVisualizationView(const QmitkUGVisualizationView& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - QmitkUGVisualizationView::~QmitkUGVisualizationView() { delete m_VolumeModeObserver; } void QmitkUGVisualizationView::CreateQtPartControl( QWidget *parent ) { m_Controls.setupUi( parent ); m_Outline2DWidget = new QmitkBoolPropertyWidget("Outline 2D polygons", parent); m_Outline2DAction = new QWidgetAction(this); m_Outline2DAction->setDefaultWidget(m_Outline2DWidget); m_LODAction = new QAction("Enable LOD (Level Of Detail)", this); m_LODAction->setCheckable(true); m_ScalarVisibilityWidget = new QmitkBoolPropertyWidget("Visualize scalars", parent); m_ScalarVisibilityAction = new QWidgetAction(this); m_ScalarVisibilityAction->setDefaultWidget(m_ScalarVisibilityWidget); m_ShowColorAction = new QAction("Show color transfer function", this); m_ShowColorAction->setCheckable(true); m_ShowColorAction->setChecked(m_ShowColorWidget); m_ShowGradientOpacityAction = new QAction("Show gradient opacity function", this); m_ShowGradientOpacityAction->setCheckable(true); m_ShowGradientOpacityAction->setChecked(m_ShowGradientOpacityWidget); m_ShowScalarOpacityAction = new QAction("Show scalar opacity function", this); m_ShowScalarOpacityAction->setCheckable(true); m_ShowScalarOpacityAction->setChecked(m_ShowScalarOpacityWidget); m_ShowTFGeneratorAction = new QAction("Show transfer function generator", this); m_ShowTFGeneratorAction->setCheckable(true); m_ShowTFGeneratorAction->setChecked(m_ShowTFGeneratorWidget); QMenu* menu = new QMenu(parent); menu->addAction(m_ScalarVisibilityAction); menu->addAction(m_Outline2DAction); //menu->addAction(m_LODAction); menu->addSeparator(); menu->addAction(m_ShowTFGeneratorAction); menu->addAction(m_ShowScalarOpacityAction); menu->addAction(m_ShowColorAction); menu->addAction(m_ShowGradientOpacityAction); m_Controls.m_OptionsButton->setMenu(menu); m_Controls.m_TransferFunctionWidget->SetScalarLabel("Scalar value"); // const mitk::EnumerationProperty::EnumStringsContainerType& scalarStrings = scalarProp->GetEnumStrings(); // for (mitk::EnumerationProperty::EnumStringsContainerType::const_iterator it = scalarStrings.begin(); // it != scalarStrings.end(); ++it) // { // MITK_INFO << "ADding: " << it->first; // m_Controls.m_ScalarModeComboBox->addItem(QString::fromStdString(it->first), it->second); // } this->UpdateGUI(); CreateConnections(); } void QmitkUGVisualizationView::CreateConnections() { connect(m_Controls.m_ScalarModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateRenderWindow())); connect(m_Controls.m_RepresentationComboBox, SIGNAL(activated(int)), this, SLOT(UpdateRenderWindow())); connect(m_Outline2DWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow())); connect(m_ScalarVisibilityWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow())); connect(m_Controls.m_TransferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()), m_Controls.m_TransferFunctionWidget, SLOT(OnUpdateCanvas())); connect(m_ShowColorAction, SIGNAL(triggered(bool)), this, SLOT(ShowColorWidget(bool))); connect(m_ShowGradientOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowGradientOpacityWidget(bool))); connect(m_ShowScalarOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowScalarOpacityWidget(bool))); connect(m_ShowTFGeneratorAction, SIGNAL(triggered(bool)), this, SLOT(ShowTFGeneratorWidget(bool))); } void QmitkUGVisualizationView::UpdateRenderWindow() { mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkUGVisualizationView::ShowTFGeneratorWidget(bool show) { m_ShowTFGeneratorWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowScalarOpacityWidget(bool show) { m_ShowScalarOpacityWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowColorWidget(bool show) { m_ShowColorWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::ShowGradientOpacityWidget(bool show) { m_ShowGradientOpacityWidget = show; UpdateEnablement(); } void QmitkUGVisualizationView::UpdateEnablement() { m_Controls.m_TransferFunctionGeneratorWidget->setVisible(m_ShowTFGeneratorWidget); m_Controls.m_TransferFunctionWidget->ShowScalarOpacityFunction(m_ShowScalarOpacityWidget); m_Controls.m_TransferFunctionWidget->ShowColorFunction(m_ShowColorWidget); m_Controls.m_TransferFunctionWidget->ShowGradientOpacityFunction(m_ShowGradientOpacityWidget); m_Controls.m_TransferFunctionGeneratorWidget->SetThresholdTabEnabled(m_ScalarVisibilityWidget->isChecked()); m_Controls.m_TransferFunctionGeneratorWidget->SetBellTabEnabled(m_ScalarVisibilityWidget->isChecked()); m_Controls.m_TransferFunctionWidget->SetScalarOpacityFunctionEnabled(m_ScalarVisibilityWidget->isChecked()); m_Controls.m_TransferFunctionWidget->SetGradientOpacityFunctionEnabled(m_VolumeMode); } void QmitkUGVisualizationView::UpdateGUI() { bool enable = false; mitk::DataNode* node = 0; std::vector nodes = this->GetDataManagerSelection(); if (!nodes.empty()) { node = nodes.front(); if (node) { // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item mitk::BaseData* data = node->GetData(); if (data) { // test if this data item is an unstructured grid enable = dynamic_cast( data ); } } } m_Controls.m_SelectedLabel->setVisible(enable); m_Controls.m_ErrorLabel->setVisible(!enable); m_Controls.m_ContainerWidget->setEnabled(enable); m_Controls.m_OptionsButton->setEnabled(enable); if (enable) { m_VolumeMode = false; node->GetBoolProperty("volumerendering", m_VolumeMode); m_Controls.m_SelectedLabel->setText(QString("Selected UG: ") + node->GetName().c_str()); m_Controls.m_TransferFunctionGeneratorWidget->SetDataNode(node); m_Controls.m_TransferFunctionWidget->SetDataNode(node); mitk::BoolProperty* outlineProp = 0; node->GetProperty(outlineProp, "outline polygons"); m_Outline2DWidget->SetProperty(outlineProp); mitk::BoolProperty* scalarVisProp = 0; node->GetProperty(scalarVisProp, "scalar visibility"); m_ScalarVisibilityWidget->SetProperty(scalarVisProp); mitk::VtkScalarModeProperty* scalarProp = 0; if (node->GetProperty(scalarProp, "scalar mode")) { m_Controls.m_ScalarModeComboBox->SetProperty(scalarProp); } mitk::GridRepresentationProperty* gridRepProp = 0; mitk::GridVolumeMapperProperty* gridVolumeProp = 0; mitk::BoolProperty* volumeProp = 0; node->GetProperty(gridRepProp, "grid representation"); node->GetProperty(gridVolumeProp, "volumerendering.mapper"); node->GetProperty(volumeProp, "volumerendering"); m_Controls.m_RepresentationComboBox->SetProperty(gridRepProp, gridVolumeProp, volumeProp); if (m_VolumeModeObserver) { delete m_VolumeModeObserver; m_VolumeModeObserver = 0; } if (volumeProp) { m_VolumeModeObserver = new UGVisVolumeObserver(volumeProp, this); } } UpdateEnablement(); } void QmitkUGVisualizationView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkUGVisualizationView::StdMultiWidgetNotAvailable() { m_MultiWidget = 0; } void QmitkUGVisualizationView::OnSelectionChanged( std::vector nodes ) { UpdateGUI(); } diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h index 89cea95486..f76aba6c1f 100644 --- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h +++ b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h @@ -1,117 +1,116 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkUGVisualizationView_h #define QmitkUGVisualizationView_h #include #include #include "ui_QmitkUGVisualizationViewControls.h" class QWidgetAction; class QmitkBoolPropertyWidget; namespace mitk { class PropertyObserver; } /*! \brief QmitkUGVisualizationView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkUGVisualizationView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkUGVisualizationView(); - QmitkUGVisualizationView(const QmitkUGVisualizationView& other); virtual ~QmitkUGVisualizationView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: void UpdateRenderWindow(); void ShowTFGeneratorWidget(bool show); void ShowScalarOpacityWidget(bool show); void ShowColorWidget(bool show); void ShowGradientOpacityWidget(bool show); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void CreateConnections(); private: friend class UGVisVolumeObserver; void UpdateGUI(); void UpdateEnablement(); Ui::QmitkUGVisualizationViewControls m_Controls; QmitkStdMultiWidget* m_MultiWidget; QWidgetAction* m_Outline2DAction; QmitkBoolPropertyWidget* m_Outline2DWidget; QAction* m_LODAction; QWidgetAction* m_ScalarVisibilityAction; QmitkBoolPropertyWidget* m_ScalarVisibilityWidget; int m_FirstVolumeRepId; QHash m_MapRepComboToEnumId; bool m_VolumeMode; bool m_ShowTFGeneratorWidget; bool m_ShowScalarOpacityWidget; bool m_ShowColorWidget; bool m_ShowGradientOpacityWidget; QAction* m_ShowTFGeneratorAction; QAction* m_ShowScalarOpacityAction; QAction* m_ShowColorAction; QAction* m_ShowGradientOpacityAction; mitk::PropertyObserver* m_VolumeModeObserver; }; #endif // _QMITKUGVISUALIZATIONVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp index ae84ebbc83..54b01ebd90 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp @@ -1,793 +1,785 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //Qmitk headers #include "QmitkViewNavigatorWidget.h" // Blueberry #include #include #include #include +#include #include - -#include +#include // Qt +#include #include #include #include #include class KeywordRegistry { public: KeywordRegistry() { - berry::IExtensionPointService::Pointer extensionPointService = berry::Platform::GetExtensionPointService(); - berry::IConfigurationElement::vector keywordExts(extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords")); - - std::string keywordId; - std::string keywordLabels; - berry::IConfigurationElement::vector::iterator keywordExtsIt; - for (keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) + berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); + auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords"); + for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) { - (*keywordExtsIt)->GetAttribute("id", keywordId); - (*keywordExtsIt)->GetAttribute("label", keywordLabels); - - if (m_Keywords.find(keywordId) == m_Keywords.end()) - { - m_Keywords[keywordId] = std::vector(); - } - m_Keywords[keywordId].push_back(QString::fromStdString(keywordLabels)); + QString keywordId = (*keywordExtsIt)->GetAttribute("id"); + QString keywordLabels = (*keywordExtsIt)->GetAttribute("label"); + m_Keywords[keywordId].push_back(keywordLabels); } } - std::vector GetKeywords(const std::string& id) + QStringList GetKeywords(const QString& id) { return m_Keywords[id]; } - std::vector GetKeywords(const std::vector& ids) + QStringList GetKeywords(const QStringList& ids) { - std::vector result; - for (unsigned int i = 0; i < ids.size(); ++i) + QStringList result; + for (int i = 0; i < ids.size(); ++i) { - std::vector< QString > tmpResult; - tmpResult = this->GetKeywords(ids[i]); - result.insert(result.end(), tmpResult.begin(), tmpResult.end()); + result.append(this->GetKeywords(ids[i])); } return result; } private: - std::map > m_Keywords; + QHash m_Keywords; }; class ClassFilterProxyModel : public QSortFilterProxyModel { private : bool hasToBeDisplayed(const QModelIndex index) const; bool displayElement(const QModelIndex index) const; public: ClassFilterProxyModel(QObject *parent = NULL); bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; ClassFilterProxyModel::ClassFilterProxyModel(QObject *parent): QSortFilterProxyModel(parent) { } bool ClassFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return hasToBeDisplayed(index); } bool ClassFilterProxyModel::displayElement(const QModelIndex index) const { bool result = false; QString type = sourceModel()->data(index, Qt::DisplayRole).toString(); QStandardItem * item = dynamic_cast(sourceModel())->itemFromIndex(index); if (type.contains(filterRegExp())) { return true; } { mitk::QtViewItem* viewItem = dynamic_cast(item); if (viewItem) { - for (unsigned int i = 0; i < viewItem->m_Tags.size(); ++i) + for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } { mitk::QtPerspectiveItem* viewItem = dynamic_cast(item); if (viewItem) { - for (unsigned int i = 0; i < viewItem->m_Tags.size(); ++i) + for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } return result; } bool ClassFilterProxyModel::hasToBeDisplayed(const QModelIndex index) const { bool result = false; if ( sourceModel()->rowCount(index) > 0 ) { for( int ii = 0; ii < sourceModel()->rowCount(index); ii++) { QModelIndex childIndex = sourceModel()->index(ii,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* p) : parentWidget(p) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED | Events::PART_CHANGED; } - void PerspectiveActivated(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer /*perspective*/) + void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } - void PerspectiveSavedAs(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer /*oldPerspective*/, - berry::IPerspectiveDescriptor::Pointer /*newPerspective*/) + void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, + const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) { } - void PerspectiveDeactivated(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer /*perspective*/) + void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } - void PerspectiveOpened(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer /*perspective*/) + void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } - void PerspectiveClosed(berry::IWorkbenchPage::Pointer /*page*/, - berry::IPerspectiveDescriptor::Pointer /*perspective*/) + void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, + const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } using IPerspectiveListener::PerspectiveChanged; - void PerspectiveChanged(berry::IWorkbenchPage::Pointer, - berry::IPerspectiveDescriptor::Pointer, - berry::IWorkbenchPartReference::Pointer partRef, const std::string& changeId) + void PerspectiveChanged(const berry::IWorkbenchPage::Pointer&, + const berry::IPerspectiveDescriptor::Pointer&, + const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId) { if (changeId=="viewHide" && partRef->GetId()=="org.mitk.views.viewnavigatorview") - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(parentWidget->m_PerspectiveListener); + berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(parentWidget->m_PerspectiveListener.data()); else parentWidget->UpdateTreeList(NULL, partRef.GetPointer(), changeId); } private: QmitkViewNavigatorWidget* parentWidget; }; struct ViewNavigatorWindowListener : public berry::IWindowListener { ViewNavigatorWindowListener(QmitkViewNavigatorWidget* switcher) : switcher(switcher) , m_Done(false) {} - virtual void WindowOpened(berry::IWorkbenchWindow::Pointer window) + virtual void WindowOpened(const berry::IWorkbenchWindow::Pointer& window) { if (m_Done) return; if ( switcher->FillTreeList() ) { m_Done = true; - switcher->m_PerspectiveListener = ViewNavigatorPerspectiveListener::Pointer(new ViewNavigatorPerspectiveListener(switcher)); - window->AddPerspectiveListener(switcher->m_PerspectiveListener); + switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); + window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); } } - virtual void WindowActivated(berry::IWorkbenchWindow::Pointer window) + virtual void WindowActivated(const berry::IWorkbenchWindow::Pointer& window) { if (m_Done) return; if ( switcher->FillTreeList() ) { m_Done = true; - switcher->m_PerspectiveListener = ViewNavigatorPerspectiveListener::Pointer(new ViewNavigatorPerspectiveListener(switcher)); - window->AddPerspectiveListener(switcher->m_PerspectiveListener); + switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); + window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); } } private: QmitkViewNavigatorWidget* switcher; bool m_Done; }; -bool compareViews(berry::IViewDescriptor::Pointer a, berry::IViewDescriptor::Pointer b) +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(berry::IPerspectiveDescriptor::Pointer a, berry::IPerspectiveDescriptor::Pointer b) +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(QStandardItem* a, QStandardItem* b) +bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b) { if (a==NULL || b==NULL) return false; return a->text().compare(b->text()) < 0; } QmitkViewNavigatorWidget::QmitkViewNavigatorWidget( QWidget * parent, Qt::WindowFlags ) : QWidget(parent) { m_Generated = false; this->CreateQtPartControl(this); } QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget() { } void QmitkViewNavigatorWidget::setFocus() { m_Controls.lineEdit->setFocus(); } void QmitkViewNavigatorWidget::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNotNull()) { - m_PerspectiveListener = ViewNavigatorPerspectiveListener::Pointer(new ViewNavigatorPerspectiveListener(this)); - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->AddPerspectiveListener(m_PerspectiveListener); + m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); + berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->AddPerspectiveListener(m_PerspectiveListener.data()); } else { - m_WindowListener = ViewNavigatorWindowListener::Pointer(new ViewNavigatorWindowListener(this)); - berry::PlatformUI::GetWorkbench()->AddWindowListener(m_WindowListener); + m_WindowListener.reset(new ViewNavigatorWindowListener(this)); + berry::PlatformUI::GetWorkbench()->AddWindowListener(m_WindowListener.data()); } m_Parent = parent; 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); //proxyModel->setFilterFixedString("Diff"); m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel); } void QmitkViewNavigatorWidget::UpdateTreeList(QStandardItem* root, berry::IWorkbenchPartReference *partRef, const std::string &changeId) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNull()) return; if( !m_Generated ) { m_Generated = FillTreeList(); } if (root==NULL) root = m_TreeModel->invisibleRootItem(); for (int i=0; irowCount(); i++) { QStandardItem* item = root->child(i); QFont font; if (dynamic_cast(item)) { mitk::QtPerspectiveItem* pItem = dynamic_cast(item); berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); if (currentPersp.IsNotNull() && currentPersp->GetId()==pItem->m_Perspective->GetId()) font.setBold(true); pItem->setFont(font); } mitk::QtViewItem* vItem = dynamic_cast(item); if (vItem) { - std::vector viewParts(page->GetViews()); - for (unsigned int i=0; i viewParts(page->GetViews()); + for (int i=0; iGetPartName()==vItem->m_View->GetLabel()) { font.setBold(true); break; } if( partRef!=NULL && partRef->GetId()==vItem->m_View->GetId() && changeId=="viewHide") font.setBold(false); vItem->setFont(font); } UpdateTreeList(item, partRef, changeId); } } bool QmitkViewNavigatorWidget::FillTreeList() { // active workbench window available? if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNull()) return false; // active page available? berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNull()) return false; // everything is fine and we can remove the window listener - if (m_WindowListener.IsNotNull()) - berry::PlatformUI::GetWorkbench()->RemoveWindowListener(m_WindowListener); + if (m_WindowListener != nullptr) + berry::PlatformUI::GetWorkbench()->RemoveWindowListener(m_WindowListener.data()); // initialize tree model m_TreeModel->clear(); QStandardItem *treeRootItem = m_TreeModel->invisibleRootItem(); // get all available perspectives berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); - std::vector perspectiveDescriptors(perspRegistry->GetPerspectives()); - std::sort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); + QList perspectiveDescriptors(perspRegistry->GetPerspectives()); + qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); // get all Keywords KeywordRegistry keywordRegistry; berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); - std::vector perspectiveExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetPerspectiveExcludeList(); + QStringList perspectiveExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetPerspectiveExcludeList(); std::vector< QStandardItem* > categoryItems; QStandardItem *perspectiveRootItem = new QStandardItem("Workflows"); perspectiveRootItem->setEditable(false); perspectiveRootItem->setFont(QFont("", 12, QFont::Normal)); treeRootItem->appendRow(perspectiveRootItem); - for (unsigned int i=0; iGetId()) { skipPerspective = true; break; } if (skipPerspective) continue; //QIcon* pIcon = static_cast(p->GetImageDescriptor()->CreateImage()); - mitk::QtPerspectiveItem* pItem = new mitk::QtPerspectiveItem(QString::fromStdString(p->GetLabel())); + mitk::QtPerspectiveItem* pItem = new mitk::QtPerspectiveItem(p->GetLabel()); pItem->m_Perspective = p; - pItem->m_Description = QString::fromStdString(p->GetDescription()); - std::vector keylist = p->GetKeywordReferences(); + pItem->m_Description = p->GetDescription(); + QStringList keylist = p->GetKeywordReferences(); pItem->m_Tags = keywordRegistry.GetKeywords(keylist); pItem->setEditable(false); QFont font; font.setBold(true); if (currentPersp.IsNotNull() && currentPersp->GetId()==p->GetId()) pItem->setFont(font); - std::vector catPath = p->GetCategoryPath(); - if (catPath.empty()) + QStringList catPath = p->GetCategoryPath(); + if (catPath.isEmpty()) { perspectiveRootItem->appendRow(pItem); } else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext().toStdString() == catPath.front()) + { + if (categoryItems.at(c)->text() == catPath.front()) { categoryItem = categoryItems.at(c); break; } + } if (categoryItem==NULL) { - categoryItem = new QStandardItem(QIcon(),catPath.front().c_str()); + categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(pItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); // get all available views berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); - std::vector viewDescriptors(viewRegistry->GetViews()); - std::vector viewParts(page->GetViews()); - std::sort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); + QList viewDescriptors(viewRegistry->GetViews()); + QList viewParts(page->GetViews()); + qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); QStandardItem* emptyItem = new QStandardItem(); emptyItem->setFlags(Qt::ItemIsEnabled); treeRootItem->appendRow(emptyItem); - std::vector viewExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetViewExcludeList(); + QStringList viewExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetViewExcludeList(); QStandardItem* viewRootItem = new QStandardItem(QIcon(),"Views"); viewRootItem->setFont(QFont("", 12, QFont::Normal)); viewRootItem->setEditable(false); treeRootItem->appendRow(viewRootItem); categoryItems.clear(); QStandardItem* noCategoryItem = new QStandardItem(QIcon(),"Miscellaneous"); noCategoryItem->setEditable(false); noCategoryItem->setFont(QFont("", 12, QFont::Normal)); - for (unsigned int i = 0; i < viewDescriptors.size(); ++i) + for (int i = 0; i < viewDescriptors.size(); ++i) { berry::IViewDescriptor::Pointer v = viewDescriptors[i]; bool skipView = false; - for(unsigned int e=0; eGetId()) { skipView = true; break; } if (skipView) continue; - std::vector catPath = v->GetCategoryPath(); + QStringList catPath = v->GetCategoryPath(); QIcon* icon = static_cast(v->GetImageDescriptor()->CreateImage()); - mitk::QtViewItem* vItem = new mitk::QtViewItem(*icon, QString::fromStdString(v->GetLabel())); + mitk::QtViewItem* vItem = new mitk::QtViewItem(*icon, v->GetLabel()); vItem->m_View = v; - vItem->setToolTip(v->GetDescription().c_str()); - vItem->m_Description = QString::fromStdString(v->GetDescription()); + vItem->setToolTip(v->GetDescription()); + vItem->m_Description = v->GetDescription(); - std::vector keylist = v->GetKeywordReferences(); + QStringList keylist = v->GetKeywordReferences(); vItem->m_Tags = keywordRegistry.GetKeywords(keylist); vItem->setEditable(false); - for (unsigned int i=0; iGetPartName()==v->GetLabel()) { QFont font; font.setBold(true); vItem->setFont(font); break; } if (catPath.empty()) noCategoryItem->appendRow(vItem); else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext().toStdString() == catPath.front()) + if (categoryItems.at(c)->text() == catPath.front()) { categoryItem = categoryItems.at(c); break; } if (categoryItem==NULL) { - categoryItem = new QStandardItem(QIcon(),catPath.front().c_str()); + categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(vItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); if (noCategoryItem->hasChildren()) viewRootItem->appendRow(noCategoryItem); m_Controls.m_PluginTreeView->expandAll(); return true; } void QmitkViewNavigatorWidget::FilterChanged() { QString filterString = m_Controls.lineEdit->text(); // if (filterString.size() > 0 ) m_Controls.m_PluginTreeView->expandAll(); // else // m_Controls.m_PluginTreeView->collapseAll(); // QRegExp::PatternSyntax syntax = QRegExp::RegExp; Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; QString strPattern = "^*" + filterString; QRegExp regExp(strPattern, caseSensitivity); m_FilterProxyModel->setFilterRegExp(regExp); } void QmitkViewNavigatorWidget::ItemClicked(const QModelIndex &index) { QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if ( dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { try { mitk::QtPerspectiveItem* pItem = dynamic_cast< mitk::QtPerspectiveItem* >(item); berry::PlatformUI::GetWorkbench()->ShowPerspective( pItem->m_Perspective->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } catch (...) { QMessageBox::critical(0, "Opening Perspective Failed", QString("The requested perspective could not be opened.\nSee the log for details.")); } } else if ( dynamic_cast< mitk::QtViewItem* >(item) ) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { try { mitk::QtViewItem* vItem = dynamic_cast< mitk::QtViewItem* >(item); page->ShowView(vItem->m_View->GetId()); } catch (berry::PartInitException e) { - BERRY_ERROR << "Error: " << e.displayText() << std::endl; + BERRY_ERROR << "Error: " << e.what() << std::endl; } } } } void QmitkViewNavigatorWidget::AddPerspective() { QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); try { berry::IPerspectiveDescriptor::Pointer perspDesc; - perspDesc = perspRegistry->CreatePerspective(dialog->GetPerspectiveName().toStdString(), perspRegistry->FindPerspectiveWithId(perspRegistry->GetDefaultPerspective())); + perspDesc = perspRegistry->CreatePerspective(dialog->GetPerspectiveName(), perspRegistry->FindPerspectiveWithId(perspRegistry->GetDefaultPerspective())); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); } catch(...) { QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); } FillTreeList(); } void QmitkViewNavigatorWidget::ClonePerspective() { if (m_RegisteredPerspective.IsNotNull()) { QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); - QString defaultName(m_RegisteredPerspective->GetLabel().c_str()); + QString defaultName = m_RegisteredPerspective->GetLabel(); defaultName.append(" Copy"); dialog->SetPerspectiveName(defaultName); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); try { - berry::IPerspectiveDescriptor::Pointer perspDesc = perspRegistry->ClonePerspective(dialog->GetPerspectiveName().toStdString(), dialog->GetPerspectiveName().toStdString(), m_RegisteredPerspective); + berry::IPerspectiveDescriptor::Pointer perspDesc = perspRegistry->ClonePerspective(dialog->GetPerspectiveName(), dialog->GetPerspectiveName(), m_RegisteredPerspective); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); } catch(...) { QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); } FillTreeList(); } } void QmitkViewNavigatorWidget::ResetPerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to reset the current perspective?", QMessageBox::Yes|QMessageBox::No).exec()) berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkViewNavigatorWidget::DeletePerspective() { if (m_RegisteredPerspective.IsNotNull()) { QString question = "Do you really want to remove the perspective '"; - question.append(m_RegisteredPerspective->GetLabel().c_str()); + question.append(m_RegisteredPerspective->GetLabel()); question.append("'?"); if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", question, QMessageBox::Yes|QMessageBox::No).exec()) { if( m_RegisteredPerspective == berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective() ) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->CloseCurrentPerspective(true, true); } berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); perspRegistry->DeletePerspective(m_RegisteredPerspective); berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->RemovePerspective(m_RegisteredPerspective); FillTreeList(); if (! berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective()) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->Close(); } } } } 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 = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->CloseCurrentPerspective(true, true); // if ( page->GetPerspective().IsNull() ) // { // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); // } } } 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 = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->CloseAllPerspectives(true, true); // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } } 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 (m_ContextMenu==NULL) return; m_ContextMenu->clear(); m_RegisteredPerspective = NULL; 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->addSeparator(); if ( item!=NULL && dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { m_RegisteredPerspective = dynamic_cast< mitk::QtPerspectiveItem* >(item)->m_Perspective; //m_ContextMenu->addSeparator(); QAction* cloneAction = new QAction("Duplicate perspective", this); m_ContextMenu->addAction(cloneAction); connect(cloneAction, SIGNAL(triggered()), SLOT(ClonePerspective())); if (!m_RegisteredPerspective->IsPredefined()) { QAction* deleteAction = new QAction("Remove perspective", this); m_ContextMenu->addAction(deleteAction); connect(deleteAction, SIGNAL(triggered()), SLOT(DeletePerspective())); } m_ContextMenu->addSeparator(); } QAction* resetAction = new QAction("Reset current perspective", this); m_ContextMenu->addAction(resetAction); connect(resetAction, SIGNAL(triggered()), SLOT(ResetPerspective())); QAction* closeAction = new QAction("Close current perspective", this); m_ContextMenu->addAction(closeAction); connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective())); m_ContextMenu->addSeparator(); QAction* closeAllAction = new QAction("Close all perspectives", this); m_ContextMenu->addAction(closeAllAction); connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives())); m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos)); } diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h index 32fe32b314..42415d6ae6 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h @@ -1,91 +1,91 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKViewNavigatorWidget_H_INCLUDED #define _QMITKViewNavigatorWidget_H_INCLUDED //QT headers #include #include #include #include "ui_QmitkViewNavigatorWidgetControls.h" #include #include #include #include #include #include #include #include #include #include #include class ClassFilterProxyModel; /** @brief */ class QmitkViewNavigatorWidget : public QWidget { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: QmitkViewNavigatorWidget (QWidget* parent = 0, Qt::WindowFlags f = 0); virtual ~QmitkViewNavigatorWidget(); virtual void CreateQtPartControl(QWidget *parent); void setFocus(); bool FillTreeList(); void UpdateTreeList(QStandardItem* item = NULL, berry::IWorkbenchPartReference* partRef=NULL, const std::string& changeId=""); - berry::IPerspectiveListener::Pointer m_PerspectiveListener; - berry::IWindowListener::Pointer m_WindowListener; + QScopedPointer m_PerspectiveListener; + QScopedPointer m_WindowListener; public slots: void CustomMenuRequested(QPoint pos); void ItemClicked(const QModelIndex &index); void AddPerspective(); void ClonePerspective(); void ResetPerspective(); void DeletePerspective(); void CloseAllPerspectives(); void ClosePerspective(); void ExpandAll(); void CollapseAll(); void FilterChanged(); protected: // member variables - Ui::QmitkViewNavigatorWidgetControls m_Controls; + Ui::QmitkViewNavigatorWidgetControls m_Controls; QWidget* m_Parent; QStandardItemModel* m_TreeModel; ClassFilterProxyModel* m_FilterProxyModel; QMenu* m_ContextMenu; berry::IPerspectiveDescriptor::Pointer m_RegisteredPerspective; bool m_Generated; private: }; #endif // _QMITKViewNavigatorWidget_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtPerspectiveItem.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtPerspectiveItem.h index 1ede7418d3..7c6588704f 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtPerspectiveItem.h +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtPerspectiveItem.h @@ -1,48 +1,48 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _PerspectiveItem #define _PerspectiveItem #include #include namespace mitk { class QtPerspectiveItem : public QStandardItem { public: QtPerspectiveItem(QString string) : QStandardItem(string) { } QtPerspectiveItem(const QIcon& icon, QString string) : QStandardItem(icon, string) { } berry::IPerspectiveDescriptor::Pointer m_Perspective; - std::vector m_Tags; + QStringList m_Tags; QString m_Description; private: }; } #endif diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtViewItem.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtViewItem.h index 04c2beeb80..6dfb0b98d5 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtViewItem.h +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/mitkQtViewItem.h @@ -1,49 +1,49 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _ViewItem #define _ViewItem #include #include #include namespace mitk { class QtViewItem : public QStandardItem { public: QtViewItem(QString string) : QStandardItem(string) { } QtViewItem(const QIcon& icon, QString string) : QStandardItem(icon, string) { } berry::IViewDescriptor::Pointer m_View; - std::vector m_Tags; + QStringList m_Tags; QString m_Description; private: }; } #endif diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h index e4d33084c7..9cc9f02169 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h @@ -1,89 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKVOLUMEVISUALIZATIONVIEW_H_ #define QMITKVOLUMEVISUALIZATIONVIEW_H_ #include -#include #include #include #include #include "mitkDataStorage.h" #include #include #include #include "ui_QmitkVolumeVisualizationViewControls.h" /** * \ingroup org_mitk_gui_qt_volumevisualization_internal */ class QmitkVolumeVisualizationView : public QmitkAbstractView { Q_OBJECT public: void SetFocus(); QmitkVolumeVisualizationView(); virtual ~QmitkVolumeVisualizationView(); virtual void CreateQtPartControl(QWidget *parent); /// /// Invoked when the DataManager selection changed /// virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes); static const std::string VIEW_ID; protected slots: void OnMitkInternalPreset( int mode ); void OnEnableRendering( bool state ); void OnEnableLOD( bool state ); void OnRenderMode( int mode ); protected: - /// - /// A selection listener for datatreenode events - /// - berry::ISelectionListener::Pointer m_SelectionListener; - Ui::QmitkVolumeVisualizationViewControls* m_Controls; private: mitk::WeakPointer m_SelectedNode; void UpdateInterface(); void NodeRemoved(const mitk::DataNode* node); }; #endif /*QMITKVOLUMEVISUALIZATIONVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp index 53cda4f0c5..569f7f8924 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp @@ -1,274 +1,274 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatConnectionPreferencePage.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryIPreferencesService.h" #include "berryPlatform.h" #include #include #include #include #include #include #include #include "ctkXnatSession.h" #include "ctkXnatLoginProfile.h" #include "ctkXnatException.h" #include using namespace berry; QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage() : m_Control(0) { } void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer ) { } void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent) { - IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); + IPreferencesService* prefService = Platform::GetPreferencesService(); berry::IPreferences::Pointer _XnatConnectionPreferencesNode = prefService->GetSystemPreferences()->Node("/XnatConnection"); m_XnatConnectionPreferencesNode = _XnatConnectionPreferencesNode; m_Controls.setupUi(parent); m_Control = new QWidget(parent); m_Control->setLayout(m_Controls.gridLayout); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch(std::invalid_argument) { session = 0; } if(session != 0) { if(session->isOpen()) { m_Controls.testConnectionButton->setText("Disconnect"); } else { m_Controls.testConnectionButton->setText("Connect"); } } const QIntValidator *portV = new QIntValidator(0, 65535, parent); m_Controls.inPort->setValidator(portV); const QRegExp hostRx("^(https?)://[^ /](\\S)+$"); const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent); m_Controls.inHostAddress->setValidator(hostV); connect( m_Controls.testConnectionButton, SIGNAL(clicked()), this, SLOT(ToggleConnection()) ); connect(m_Controls.inHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged())); connect(m_Controls.inDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged())); this->Update(); } QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const { return m_Control; } bool QmitkXnatConnectionPreferencePage::PerformOk() { if(!UserInformationEmpty()) { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if(_XnatConnectionPreferencesNode.IsNotNull()) { - _XnatConnectionPreferencesNode->Put(m_Controls.hostAddressLabel->text().toStdString(), m_Controls.inHostAddress->text().toStdString()); - _XnatConnectionPreferencesNode->Put(m_Controls.portLabel->text().toStdString(), m_Controls.inPort->text().toStdString()); - _XnatConnectionPreferencesNode->Put(m_Controls.usernameLabel->text().toStdString(), m_Controls.inUsername->text().toStdString()); - _XnatConnectionPreferencesNode->Put(m_Controls.passwortLabel->text().toStdString(), m_Controls.inPassword->text().toStdString()); - _XnatConnectionPreferencesNode->Put(m_Controls.downloadPathLabel->text().toStdString(), m_Controls.inDownloadPath->text().toStdString()); + _XnatConnectionPreferencesNode->Put(m_Controls.hostAddressLabel->text(), m_Controls.inHostAddress->text()); + _XnatConnectionPreferencesNode->Put(m_Controls.portLabel->text(), m_Controls.inPort->text()); + _XnatConnectionPreferencesNode->Put(m_Controls.usernameLabel->text(), m_Controls.inUsername->text()); + _XnatConnectionPreferencesNode->Put(m_Controls.passwortLabel->text(), m_Controls.inPassword->text()); + _XnatConnectionPreferencesNode->Put(m_Controls.downloadPathLabel->text(), m_Controls.inDownloadPath->text()); _XnatConnectionPreferencesNode->Flush(); return true; } } else { QMessageBox::critical(QApplication::activeWindow(), "Saving Preferences failed", "The connection parameters in XNAT Preferences were empty.\nPlease use the 'Connect' button to validate the connection parameters."); } return false; } void QmitkXnatConnectionPreferencePage::PerformCancel() { } bool QmitkXnatConnectionPreferencePage::UserInformationEmpty() { // To check empty QLineEdits in the following QString errString; if(m_Controls.inHostAddress->text().isEmpty()) { errString += "Server Address is empty.\n"; } if(m_Controls.inUsername->text().isEmpty()) { errString += "Username is empty.\n"; } if(m_Controls.inPassword->text().isEmpty()) { errString += "Password is empty.\n"; } // if something is empty if(!errString.isEmpty()) { m_Controls.testConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.testConnectionLabel->setText("Connecting failed.\n" + errString); return true; } else { return false; } } void QmitkXnatConnectionPreferencePage::Update() { IPreferences::Pointer _XnatConnectionPreferencesNode = m_XnatConnectionPreferencesNode.Lock(); if(_XnatConnectionPreferencesNode.IsNotNull()) { - m_Controls.inHostAddress->setText(QString::fromStdString(_XnatConnectionPreferencesNode->Get( - m_Controls.hostAddressLabel->text().toStdString(), m_Controls.inHostAddress->text().toStdString()))); - m_Controls.inPort->setText(QString::fromStdString(_XnatConnectionPreferencesNode->Get( - m_Controls.portLabel->text().toStdString(), m_Controls.inPort->text().toStdString()))); - m_Controls.inUsername->setText(QString::fromStdString(_XnatConnectionPreferencesNode->Get( - m_Controls.usernameLabel->text().toStdString(), m_Controls.inUsername->text().toStdString()))); - m_Controls.inPassword->setText(QString::fromStdString(_XnatConnectionPreferencesNode->Get( - m_Controls.passwortLabel->text().toStdString(), m_Controls.inPassword->text().toStdString()))); - m_Controls.inDownloadPath->setText(QString::fromStdString(_XnatConnectionPreferencesNode->Get( - m_Controls.downloadPathLabel->text().toStdString(), m_Controls.inDownloadPath->text().toStdString()))); + m_Controls.inHostAddress->setText(_XnatConnectionPreferencesNode->Get( + m_Controls.hostAddressLabel->text(), m_Controls.inHostAddress->text())); + m_Controls.inPort->setText(_XnatConnectionPreferencesNode->Get( + m_Controls.portLabel->text(), m_Controls.inPort->text())); + m_Controls.inUsername->setText(_XnatConnectionPreferencesNode->Get( + m_Controls.usernameLabel->text(), m_Controls.inUsername->text())); + m_Controls.inPassword->setText(_XnatConnectionPreferencesNode->Get( + m_Controls.passwortLabel->text(), m_Controls.inPassword->text())); + m_Controls.inDownloadPath->setText(_XnatConnectionPreferencesNode->Get( + m_Controls.downloadPathLabel->text(), m_Controls.inDownloadPath->text())); } } void QmitkXnatConnectionPreferencePage::UrlChanged() { m_Controls.inHostAddress->setStyleSheet("QLineEdit { background-color: white; }"); QString str = m_Controls.inHostAddress->text(); while(str.endsWith("/")) { str = str.left(str.length()-1); } m_Controls.inHostAddress->setText(str); QUrl url(m_Controls.inHostAddress->text()); if(!url.isValid()) { m_Controls.inHostAddress->setStyleSheet("QLineEdit { background-color: red; }"); } } void QmitkXnatConnectionPreferencePage::DownloadPathChanged() { m_Controls.inDownloadPath->setStyleSheet("QLineEdit { background-color: white; }"); if(!m_Controls.inDownloadPath->text().isEmpty()) { QFileInfo path(m_Controls.inDownloadPath->text()); if(!path.isDir()) { m_Controls.inDownloadPath->setStyleSheet("QLineEdit { background-color: red; }"); } } } void QmitkXnatConnectionPreferencePage::ToggleConnection() { ctkXnatSession* session = 0; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch(std::invalid_argument) { if(!UserInformationEmpty()) { PerformOk(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession(); session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } } if(session != 0 && session->isOpen()) { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); m_Controls.testConnectionButton->setText("Connect"); m_Controls.testConnectionLabel->clear(); } else if(session != 0 && !session->isOpen()) { m_Controls.testConnectionButton->setEnabled(false); try { mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession(); m_Controls.testConnectionButton->setText("Disconnect"); m_Controls.testConnectionLabel->setStyleSheet("QLabel { color: green; }"); m_Controls.testConnectionLabel->setText("Connecting successful."); } catch(const ctkXnatAuthenticationException& auth) { m_Controls.testConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.testConnectionLabel->setText("Connecting failed:\nAuthentication error."); MITK_INFO << auth.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } catch(const ctkException& e) { m_Controls.testConnectionLabel->setStyleSheet("QLabel { color: red; }"); m_Controls.testConnectionLabel->setText("Connecting failed:\nInvalid Server Adress"); MITK_INFO << e.message().toStdString(); mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession(); } m_Controls.testConnectionButton->setEnabled(true); } } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp index 5384724309..b1f627a41b 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp @@ -1,500 +1,495 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatEditor.h" // Qmitk #include "QmitkXnatObjectEditorInput.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" // CTK XNAT Core #include "ctkXnatObject.h" #include "ctkXnatDataModel.h" #include "ctkXnatScanFolder.h" #include "ctkXnatFile.h" // CTK XNAT Widgets #include "ctkXnatListModel.h" // Blueberry #include #include +#include // Qt #include #include #include #include #include // MITK #include #include -const std::string QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser"; +const QString QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser"; QmitkXnatEditor::QmitkXnatEditor() : - m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()), - m_Session(0), + m_DownloadPath(berry::Platform::GetPreferencesService()-> + GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "")), m_ListModel(new ctkXnatListModel()), - m_SelectionListener(new berry::SelectionChangedAdapter(this, &QmitkXnatEditor::SelectionChanged)), - m_DownloadPath(berry::Platform::GetServiceRegistry(). - GetServiceById(berry::IPreferencesService::ID)-> - GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "").c_str()) + m_Session(0), + m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()), + m_SelectionListener(new berry::SelectionChangedAdapter(this, &QmitkXnatEditor::SelectionChanged)) { m_DataStorageServiceTracker.open(); if(m_DownloadPath.isEmpty()) { QString xnatFolder = "XNAT_DOWNLOADS"; QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath()); dir.mkdir(xnatFolder); dir.setPath(dir.path() + "/" + xnatFolder); m_DownloadPath = dir.path() + "/"; } } QmitkXnatEditor::~QmitkXnatEditor() { delete m_ListModel; berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); - s->RemoveSelectionListener(m_SelectionListener); + s->RemoveSelectionListener(m_SelectionListener.data()); m_DataStorageServiceTracker.close(); } bool QmitkXnatEditor::IsDirty() const { return false; } bool QmitkXnatEditor::IsSaveAsAllowed() const { return false; } void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { this->SetSite(site); berry::QtEditorPart::SetInput(input); this->SetInput(input); } void QmitkXnatEditor::DoSave() { } void QmitkXnatEditor::DoSaveAs() { } void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input) { QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast(); if(oPtr.IsNotNull()) { berry::QtEditorPart::SetInput(oPtr); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); } } void QmitkXnatEditor::SetFocus() { } void QmitkXnatEditor::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); - GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener); + GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data()); connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&)) ); connect( m_Controls.buttonDownloadResource, SIGNAL(clicked()), this, SLOT(DownloadResource()) ); connect( m_Controls.buttonDownloadFile, SIGNAL(clicked()), this, SLOT(DownloadFile()) ); connect( m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked()) ); connect( m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked()) ); connect( m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked()) ); connect( m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked()) ); connect( m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked()) ); connect( m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked()) ); connect( m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked()) ); m_Tracker = new mitk::XnatSessionTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()); connect( m_Tracker, SIGNAL(AboutToBeClosed(ctkXnatSession*)), this, SLOT(CleanListModel(ctkXnatSession*)) ); connect( m_Tracker, SIGNAL(Opened(ctkXnatSession*)), this, SLOT(UpdateSession(ctkXnatSession*)) ); m_Tracker->Open(); // Makes the breadcrumb feature invisible for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } QmitkXnatObjectEditorInput::Pointer oPtr = GetEditorInput().Cast(); if(oPtr.IsNotNull()) { UpdateList(); } else { ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch(std::invalid_argument) { session = 0; } UpdateSession(session); } } void QmitkXnatEditor::UpdateList() { QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast()); if( xoPtr.IsNull() ) return; ctkXnatObject* inputObject = xoPtr->GetXnatObject(); if( inputObject == NULL ) return; m_Controls.treeView->setModel(m_ListModel); m_ListModel->setRootObject( inputObject ); m_Controls.treeView->reset(); // recursive method to check parents of the inputObject m_ParentCount = ParentChecker(inputObject); // breadcrumb labels for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(false); } for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++) { QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i); child->widget()->setVisible(false); } ctkXnatObject* parent = NULL; for(int i = m_ParentCount*2; i >= 0; i--) { if(i > 12) break; m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true); QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i); child->widget()->setVisible(true); if(i>0) { m_Controls.breadcrumbHorizontalLayout->itemAt(i-1)->widget()->setVisible(true); m_Controls.breadcrumbDescriptionLayout->itemAt(i-1)->widget()->setVisible(true); } if(parent == NULL) { parent = inputObject; } // create breadcrumb button QPushButton* breadcrumbButton = dynamic_cast(child->widget()); breadcrumbButton->setText(parent->id()); parent = parent->parent(); i--; } m_Controls.buttonDataModel->setText("root"); } -void QmitkXnatEditor::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, - berry::ISelection::ConstPointer selection) +void QmitkXnatEditor::SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, + const berry::ISelection::ConstPointer& selection) { // check for null selection if (selection.IsNull()) { return; } // exclude own selection events and check whether this kind of selection can be handled if (sourcepart != this && selection.Cast()) { berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast(); // iterates over the selection for (berry::IStructuredSelection::iterator itr = currentSelection->Begin(); itr != currentSelection->End(); ++itr) { if (berry::SmartPointer objectPointer = itr->Cast()) { // get object of selected ListWidgetElement ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value(); // if a file is selected, don't change the input and list view if ( dynamic_cast(object) == NULL ) { - QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( object ); + QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput( object )); berry::IEditorInput::Pointer editorInput( oPtr ); if ( !(editorInput == this->GetEditorInput()) ) this->SetInput(editorInput); UpdateList(); } } } } } void QmitkXnatEditor::DownloadResource() { if (!m_Controls.treeView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); QVariant variant = m_ListModel->data(index, Qt::UserRole); if ( variant.isValid() ) { ctkXnatScanFolder* resource = dynamic_cast(variant.value()); if (resource != NULL) { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString resourcePath = m_DownloadPath + resource->id() + ".zip"; resource->download(resourcePath); // Testing if the path exists QDir downDir(m_DownloadPath); if( downDir.exists(resource->id() + ".zip") ) { MITK_INFO << "Download of " << resource->id().toStdString() << ".zip was completed!"; } else { MITK_INFO << "Download of " << resource->id().toStdString() << ".zip failed!"; } } else { MITK_INFO << "Selection was not a resource folder!"; } } } void QmitkXnatEditor::DownloadFile() { if (!m_Controls.treeView->selectionModel()->hasSelection()) return; const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex(); InternalFileDownload(index); } void QmitkXnatEditor::ToHigherLevel() { ctkXnatObject* parent = GetEditorInput().Cast()->GetXnatObject()->parent(); if( parent == NULL) { return; } - QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( parent ); + QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(parent)); berry::IEditorInput::Pointer editorInput( oPtr ); this->SetInput(editorInput); UpdateList(); } void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index) { if (!index.isValid()) return; ctkXnatObject* child = GetEditorInput().Cast()->GetXnatObject()->children().at(index.row()); if( child != NULL ) { ctkXnatFile* file = dynamic_cast(child); if( file != NULL ) { // Download file and put into datamanager InternalFileDownload(index); mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService(); if(dsService != NULL) { - mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode((m_DownloadPath + file->id()).toStdString()); - if ( ( node.IsNotNull() ) && ( node->GetData() != NULL ) ) - { - dsService->GetDataStorage()->GetDataStorage()->Add(node); - mitk::BaseData::Pointer basedata = node->GetData(); - mitk::RenderingManager::GetInstance()->InitializeViews( - basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); - } + mitk::IOUtil::Load((m_DownloadPath + file->id()).toStdString(), + *dsService->GetDataStorage()->GetDataStorage()); + mitk::RenderingManager::GetInstance()->InitializeViews(); } } else { // Updates the root item - QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( child ); + QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(child)); berry::IEditorInput::Pointer editorInput( oPtr ); this->SetInput(editorInput); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); UpdateList(); } } } void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index) { QVariant variant = m_ListModel->data(index, Qt::UserRole); if ( variant.isValid() ) { ctkXnatFile* file = dynamic_cast(variant.value()); if (file != NULL) { MITK_INFO << "Download started ..."; MITK_INFO << "..."; QString filePath = m_DownloadPath + file->id(); file->download(filePath); // Testing if the file exists QDir downDir(m_DownloadPath); if( downDir.exists(file->id()) ) { MITK_INFO << "Download of " << file->id().toStdString() << " was completed!"; } else { MITK_INFO << "Download of " << file->id().toStdString() << " failed!"; } } else { MITK_INFO << "Selection was not a file!"; } } } int QmitkXnatEditor::ParentChecker(ctkXnatObject* child) { int sum; if( child->parent() == NULL ) { return 0; } else { sum = 1 + ParentChecker(child->parent()); } return sum; } void QmitkXnatEditor::OnDataModelButtonClicked() { for(int i = m_ParentCount; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnProjectButtonClicked() { for(int i = m_ParentCount-1; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSubjectButtonClicked() { for(int i = m_ParentCount-2; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnExperimentButtonClicked() { for(int i = m_ParentCount-3; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnKindOfDataButtonClicked() { for(int i = m_ParentCount-4; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnSessionButtonClicked() { for(int i = m_ParentCount-5; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::OnResourceButtonClicked() { for(int i = m_ParentCount-6; i > 0; i--) { ToHigherLevel(); } } void QmitkXnatEditor::UpdateSession(ctkXnatSession* session) { - GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener); + GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data()); if(session != 0 && session->isOpen()) { m_Controls.labelInfo->setText("Current Position:"); m_Controls.labelInfo->setStyleSheet("QLabel { color: black; }"); m_Controls.buttonDownloadFile->setEnabled(true); m_Controls.buttonDownloadResource->setEnabled(true); // Fill model and show in the GUI - QmitkXnatObjectEditorInput::Pointer xoPtr = QmitkXnatObjectEditorInput::New( session->dataModel() ); + QmitkXnatObjectEditorInput::Pointer xoPtr(new QmitkXnatObjectEditorInput(session->dataModel())); berry::IEditorInput::Pointer editorInput( xoPtr ); this->SetInput(editorInput); this->GetEditorInput().Cast()->GetXnatObject()->fetch(); UpdateList(); } else { m_Controls.labelInfo->setText("Please check the Preferences of the XNAT Connection.\nMaybe they are not ok."); m_Controls.labelInfo->setStyleSheet("QLabel { color: red; }"); m_Controls.buttonDownloadFile->setEnabled(false); m_Controls.buttonDownloadResource->setEnabled(false); } - GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener); + GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data()); } void QmitkXnatEditor::CleanListModel(ctkXnatSession* session) { if(session != 0) { m_Controls.treeView->setModel(0); m_ListModel->setRootObject(0); m_Controls.treeView->reset(); m_Controls.buttonDownloadFile->setEnabled(false); m_Controls.buttonDownloadResource->setEnabled(false); } } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.h index d278fd376d..1299a47749 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.h @@ -1,130 +1,131 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKXNATEDITOR_h #define QMITKXNATEDITOR_h #include #include #include #include #include #include "ui_QmitkXnatEditorControls.h" #include "ctkXnatListModel.h" #include "ctkXnatSession.h" #include #include "mitkXnatSessionTracker.h" /*! \brief QmitkXnatEditor \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup ${plugin_target}_internal */ class QmitkXnatEditor : public berry::QtEditorPart, public berry::IReusableEditor { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: berryObjectMacro(QmitkXnatEditor) QmitkXnatEditor(); ~QmitkXnatEditor(); - static const std::string EDITOR_ID; + static const QString EDITOR_ID; void CreateQtPartControl(QWidget *parent); void DoSave(/*IProgressMonitor monitor*/); void DoSaveAs(); void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input); bool IsDirty() const; bool IsSaveAsAllowed() const; void SetInput(berry::IEditorInput::Pointer input); /** \brief Here the root object will be set and the view reset. Additionally the breadcrumbs will set visible. */ void UpdateList(); protected slots: /** \brief A resource folder will be downloaded to the chosen download path. */ void DownloadResource(); /** \brief A file will be downloaded to the chosen download path. */ void DownloadFile(); /** \brief Every time you activate a node in the list, the root item will be updated to a child of the previous parent.\ In exception of the node is a file. The file will be downloaded and loaded to the DataManager. */ void OnObjectActivated(const QModelIndex& index); // Breadcrumb button slots void OnDataModelButtonClicked(); void OnProjectButtonClicked(); void OnSubjectButtonClicked(); void OnExperimentButtonClicked(); void OnKindOfDataButtonClicked(); void OnSessionButtonClicked(); void OnResourceButtonClicked(); /// \brief Updates the ctkXnatSession and the user interface void UpdateSession(ctkXnatSession* session); void CleanListModel(ctkXnatSession* session); protected: virtual void SetFocus(); Ui::QmitkXnatEditorControls m_Controls; private: int m_ParentCount; QString m_DownloadPath; ctkServiceTracker m_DataStorageServiceTracker; void InternalFileDownload(const QModelIndex& index); int ParentChecker(ctkXnatObject* child); void ToHigherLevel(); ctkXnatListModel* m_ListModel; ctkXnatSession* m_Session; mitk::XnatSessionTracker* m_Tracker; - berry::ISelectionListener::Pointer m_SelectionListener; - void SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); + QScopedPointer m_SelectionListener; + void SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart, + const berry::ISelection::ConstPointer& selection); }; #endif // QMITKXNATEDITOR_h diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp index a0d2d584de..3ca9e92bca 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp @@ -1,63 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatObjectEditorInput.h" QmitkXnatObjectEditorInput::QmitkXnatObjectEditorInput(ctkXnatObject* object) : m_Object(object) { } QmitkXnatObjectEditorInput::~QmitkXnatObjectEditorInput() { } ctkXnatObject* QmitkXnatObjectEditorInput::GetXnatObject() const { return m_Object; } bool QmitkXnatObjectEditorInput::Exists() const { return m_Object->exists(); } -std::string QmitkXnatObjectEditorInput::GetName() const +QString QmitkXnatObjectEditorInput::GetName() const { - return m_Object->id().toStdString(); + return m_Object->id(); } -std::string QmitkXnatObjectEditorInput::GetToolTipText() const +QString QmitkXnatObjectEditorInput::GetToolTipText() const { - return m_Object->description().toStdString(); + return m_Object->description(); } bool QmitkXnatObjectEditorInput::operator==(const berry::Object* o) const { if ( const QmitkXnatObjectEditorInput* other = dynamic_cast(o) ) { if ( other->GetXnatObject()->parent() ) { return (other->GetName() == this->GetName()) && (other->GetXnatObject()->parent()->id() == this->GetXnatObject()->parent()->id()); } else { return (other->GetName() == this->GetName()); } } return false; } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h index ab5699f470..a21eaa697d 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h @@ -1,45 +1,44 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKXNATOBJECTEDITORINPUT_H_ #define QMITKXNATOBJECTEDITORINPUT_H_ #include "berryIEditorInput.h" #include "ctkXnatObject.h" class QmitkXnatObjectEditorInput : public berry::IEditorInput { public: berryObjectMacro(QmitkXnatObjectEditorInput); - berryNewMacro1Param(QmitkXnatObjectEditorInput, ctkXnatObject*); + QmitkXnatObjectEditorInput(ctkXnatObject* object); ~QmitkXnatObjectEditorInput(); /// \brief Returns the kept ctkXnatObject. ctkXnatObject* GetXnatObject() const; virtual bool Exists() const; - virtual std::string GetName() const; - virtual std::string GetToolTipText() const; + virtual QString GetName() const; + virtual QString GetToolTipText() const; virtual bool operator==(const berry::Object* o) const; private: - QmitkXnatObjectEditorInput(ctkXnatObject* object); ctkXnatObject* m_Object; }; #endif /*QMITKXNATOBJECTEDITORINPUT_H_*/ diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp index 2481263ebc..142fb9cefd 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.cpp @@ -1,89 +1,87 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatSessionManager.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" #include "berryPlatform.h" #include "berryIPreferences.h" #include "mitkLogMacros.h" #include #include #include "ctkXnatSession.h" #include "ctkXnatException.h" QmitkXnatSessionManager::QmitkXnatSessionManager() - :m_Session(0) + : m_Session(0) { - m_PreferencesService = berry::Platform::GetServiceRegistry(). - GetServiceById(berry::IPreferencesService::ID); } QmitkXnatSessionManager::~QmitkXnatSessionManager() { if(m_SessionRegistration != 0) { m_SessionRegistration.Unregister(); } if(m_Session != 0) { delete m_Session; } } void QmitkXnatSessionManager::OpenXnatSession() { ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(m_SessionRegistration.GetReference()); if(session == NULL) return; if(!session->isOpen()) { session->open(); } } void QmitkXnatSessionManager::CreateXnatSession() { - berry::IPreferencesService::Pointer prefService = m_PreferencesService.Lock(); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer nodeConnectionPref = prefService->GetSystemPreferences()->Node("/XnatConnection"); - QUrl url(QString::fromStdString(nodeConnectionPref->Get("Server Address", ""))); - url.setPort(QString::fromStdString(nodeConnectionPref->Get("Port", "")).toInt()); + QUrl url(nodeConnectionPref->Get("Server Address", "")); + url.setPort(nodeConnectionPref->Get("Port", "").toInt()); ctkXnatLoginProfile profile; profile.setName("Default"); profile.setServerUrl(url); - profile.setUserName(QString::fromStdString(nodeConnectionPref->Get("Username", ""))); - profile.setPassword(QString::fromStdString(nodeConnectionPref->Get("Password", ""))); + profile.setUserName(nodeConnectionPref->Get("Username", "")); + profile.setPassword(nodeConnectionPref->Get("Password", "")); profile.setDefault(true); m_Session = new ctkXnatSession(profile); m_SessionRegistration = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->RegisterService(m_Session); } void QmitkXnatSessionManager::CloseXnatSession() { ctkXnatSession* session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(m_SessionRegistration.GetReference()); session->close(); m_SessionRegistration.Unregister(); m_SessionRegistration = 0; delete m_Session; m_Session = 0; } diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h index c1b9865398..eae3baa392 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatSessionManager.h @@ -1,54 +1,53 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKXNATSESSIONMANAGER_H_ #define QMITKXNATSESSIONMANAGER_H_ #include #include "ctkXnatLoginProfile.h" #include "mitkXnatSessionTracker.h" class QmitkXnatSessionManager { public: QmitkXnatSessionManager(); ~QmitkXnatSessionManager(); /// \brief Opens a xnat session. void OpenXnatSession(); /// \brief Creates the xnat session. void CreateXnatSession(); void CloseXnatSession(); bool LastSessionIsValid(); int AmountOfCreatedSessions(); private: us::ServiceRegistration m_SessionRegistration; - berry::IPreferencesService::WeakPtr m_PreferencesService; ctkXnatSession* m_Session; }; #endif /*QMITKXNATSESSIONMANAGER_H_*/ diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp index 7ae25ab6b7..f671f8310b 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatTreeBrowserView.cpp @@ -1,161 +1,161 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkXnatTreeBrowserView.h" // Qmitk #include "QmitkXnatObjectEditorInput.h" #include "QmitkXnatEditor.h" #include "org_mitk_gui_qt_xnatinterface_Activator.h" // Blueberry #include // CTK XNAT Core #include "ctkXnatFile.h" const std::string QmitkXnatTreeBrowserView::VIEW_ID = "org.mitk.views.xnat.treebrowser"; QmitkXnatTreeBrowserView::QmitkXnatTreeBrowserView(): m_TreeModel(new ctkXnatTreeModel()), m_Tracker(0) { } QmitkXnatTreeBrowserView::~QmitkXnatTreeBrowserView() { delete m_TreeModel; delete m_Tracker; } void QmitkXnatTreeBrowserView::SetFocus() { } void QmitkXnatTreeBrowserView::CreateQtPartControl( QWidget *parent ) { // Create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); m_Controls.treeView->setModel(m_TreeModel); m_Controls.treeView->header()->hide(); m_Controls.labelError->setText("Please use the 'Connect' button in the Preferences."); m_Controls.labelError->setStyleSheet("QLabel { color: red; }"); m_SelectionProvider = new berry::QtSelectionProvider(); this->SetSelectionProvider(); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Tracker = new mitk::XnatSessionTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()); connect( m_Tracker, SIGNAL(AboutToBeClosed(ctkXnatSession*)), this, SLOT(CleanTreeModel(ctkXnatSession*)) ); connect( m_Tracker, SIGNAL(Opened(ctkXnatSession*)), this, SLOT(UpdateSession(ctkXnatSession*)) ); m_Tracker->Open(); ctkXnatSession* session; try { session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService( mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference()); } catch(std::invalid_argument) { session = 0; } if(session != 0) { m_Controls.labelError->setVisible(false); } else { m_Controls.labelError->setVisible(true); } connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnActivatedNode(const QModelIndex&)) ); } void QmitkXnatTreeBrowserView::OnActivatedNode(const QModelIndex& index) { if (!index.isValid()) return; berry::IWorkbenchPage::Pointer page = GetSite()->GetPage(); - QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( index.data(Qt::UserRole).value() ); + QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(index.data(Qt::UserRole).value())); berry::IEditorInput::Pointer editorInput( oPtr ); berry::IEditorPart::Pointer reuseEditor = page->FindEditor(editorInput); if(reuseEditor) { // Just set it activ page->Activate(reuseEditor); } else { - std::vector editors = + QList editors = page->FindEditors(berry::IEditorInput::Pointer(0), QmitkXnatEditor::EDITOR_ID, berry::IWorkbenchPage::MATCH_ID); - if (editors.empty()) + if (editors.isEmpty()) { // No XnatEditor is currently open, create a new one ctkXnatFile* file = dynamic_cast(oPtr->GetXnatObject()); if(file != NULL) { // If a file is activated take the parent and open a new editor - QmitkXnatObjectEditorInput::Pointer oPtr2 = QmitkXnatObjectEditorInput::New( file->parent() ); + QmitkXnatObjectEditorInput::Pointer oPtr2(new QmitkXnatObjectEditorInput( file->parent() )); berry::IEditorInput::Pointer editorInput2( oPtr2 ); page->OpenEditor(editorInput2, QmitkXnatEditor::EDITOR_ID); } else { page->OpenEditor(editorInput, QmitkXnatEditor::EDITOR_ID); } } else { // Reuse an existing editor reuseEditor = editors.front()->GetEditor(true); page->ReuseEditor(reuseEditor.Cast(), editorInput); page->Activate(reuseEditor); } } } void QmitkXnatTreeBrowserView::SetSelectionProvider() { GetSite()->SetSelectionProvider(m_SelectionProvider); } void QmitkXnatTreeBrowserView::UpdateSession(ctkXnatSession* session) { if(session != 0 && session->isOpen()) { m_Controls.labelError->setVisible(false); // Fill model and show in the GUI m_TreeModel->addDataModel(session->dataModel()); m_Controls.treeView->reset(); m_SelectionProvider->SetItemSelectionModel(m_Controls.treeView->selectionModel()); } } void QmitkXnatTreeBrowserView::CleanTreeModel(ctkXnatSession* session) { if(session != 0) { m_TreeModel->removeDataModel(session->dataModel()); m_Controls.treeView->reset(); } } diff --git a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp index 5876ea06d8..b035cec4ff 100644 --- a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp +++ b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp @@ -1,111 +1,111 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "org_mitk_simulation_Activator.h" #include #include #include #include #include #include #include #include #include #include #include static void RegisterSofaClasses() { int MeshMitkLoaderClass = sofa::core::RegisterObject("").add(); boost::ignore_unused(MeshMitkLoaderClass); } static void LoadSofaPlugins() { berry::IPreferences::Pointer preferences = mitk::GetSimulationPreferences(); if (preferences.IsNull()) return; - QString plugins = preferences->GetByteArray("plugins", "").c_str(); + QString plugins = preferences->Get("plugins", ""); if (plugins.isEmpty()) return; QStringList pluginList = plugins.split(';', QString::SkipEmptyParts); QStringListIterator it(pluginList); typedef sofa::helper::system::PluginManager PluginManager; PluginManager& pluginManager = PluginManager::getInstance(); while (it.hasNext()) { std::string plugin = it.next().toStdString(); std::ostringstream errlog; pluginManager.loadPlugin(plugin, &errlog); if (errlog.str().empty()) pluginManager.getPluginMap()[plugin].initExternalModule(); } } static void AddPropertyFilters() { mitk::IPropertyFilters* filters = mitk::org_mitk_simulation_Activator::GetService(); if (filters == NULL) return; mitk::PropertyFilter filter; filter.AddEntry("layer", mitk::PropertyFilter::Blacklist); filter.AddEntry("name", mitk::PropertyFilter::Blacklist); filter.AddEntry("path", mitk::PropertyFilter::Blacklist); filter.AddEntry("selected", mitk::PropertyFilter::Blacklist); filter.AddEntry("visible", mitk::PropertyFilter::Blacklist); filters->AddFilter(filter, "Simulation"); } ctkPluginContext* mitk::org_mitk_simulation_Activator::Context = NULL; void mitk::org_mitk_simulation_Activator::start(ctkPluginContext* context) { Context = context; RegisterSimulationObjectFactory(); RegisterSofaClasses(); LoadSofaPlugins(); AddPropertyFilters(); QmitkNodeDescriptorManager* nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance(); if (nodeDescriptorManager != NULL) { mitk::NodePredicateDataType::Pointer simulationPredicate = mitk::NodePredicateDataType::New("Simulation"); nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("Simulation", ":/Simulation/SOFAIcon.png", simulationPredicate, nodeDescriptorManager)); } } void mitk::org_mitk_simulation_Activator::stop(ctkPluginContext*) { Context = NULL; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_simulation, mitk::org_mitk_simulation_Activator) #endif diff --git a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp b/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp index ebd475cffb..ecbccb38ca 100644 --- a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp +++ b/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp @@ -1,25 +1,24 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkGetSimulationPreferences.h" #include #include -#include berry::IPreferences::Pointer mitk::GetSimulationPreferences() { - return berry::Platform::GetServiceRegistry().GetServiceById(berry::IPreferencesService::ID)->GetSystemPreferences()->Node("/org.mitk.views.simulation"); + return berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.simulation"); }